Python Program to shift Numbers

Python program to shift positive numbers at the left-hand side and negative number at the right-hand side. The program takes a list of positive and negative numbers as input and shifts the elements.

Example :
let a list contains = [-2, 1, -3, -15, 16, -17, 5, -3, -6] 
after processing the list should look like this
                     [1, 16, 5, -6, -3, -17, -15, -3, -2]

Python Program to shift Numbers

This program can be written in many ways but the simplest method is to traverse list from left to right and append element into another list.

list1 = [-2, 1, -3, -15, 16, -17, 5, -3, -6]
list2 = []
n = len(list1)

for x in range(n):
    if list1[x] > 0:
        list2.append(list1[x])

for x in range(n-1, -1, -1):
    if(list1[x]) < 0:
        list2.append(list1[x])

print(list2)

The output of the above program is as follows

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\list\shifting_number.py"
[1, 16, 5, -6, -3, -17, -15, -3, -2]

If you have any better solution for the same.Please let us know via our email.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.