pls answer computer experts
Attachments:
Answers
Answered by
6
Required Answer:-
Question:
- Write a program in python to shift negative numbers to left and positive numbers to right in a list.
Solution:
Here is the code. I have added comments so that you can understand well.
l=[] #declaring list
n=int(input("How many elements?? ")) # asking the user for the number of elements.
print("Enter them...")
for i in range(0,n):
l.append(int(input("Enter: "))) # adding elements in the list.
p=[l[i] for i in range(0,n) if l[i]>=0] # adding all the positive elements of the list l and storing here.
n=[l[i] for i in range(0,n) if l[i]<0] # adding all the negative elements of the list l and storing here.
l=[*n,*p] # Now, list l contains elements of list n at first and then elements of list p at last.
# Now print the list.
print(l)
Explanation:
- In this program, we have created a list named l in which, we have stored all the values entered by the user. Now, we will store all the positive values in list a which is present in the list l. Similarly, we will store all the negative values of list l in list n. Now, we will store elements of list n and p in this list and it gets updated. Now, the list contains negative numbers at the left and positive numbers at the right.
Output is attached.
Attachments:
Similar questions