Home > Python >Python Exercise: Sort List By Parity

Sort List By Parity

Given a list of positive integers, write a function to return a new list with all the even numbers following by all odd numbers. There are many possible results, you only need to return one result as long as it is correct.

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

You need login to comment

Solution submitted by Daniel at March 24, 2020, 6:58 p.m.
l = [5,6,10,9,40] print("Input is", l) for item in l: if item%2 != 0: l.remove(item) l.append(item) print("Output is", l)
Solution submitted by Dzeng at March 25, 2020, 11:45 p.m.
listtosort = [4,2,5,2,3,4,5,6,2,4,6,8,7,78,6,7,35,3,45,5,6] sortedlist = [] savednum = 0 for i in range(len(listtosort)): if listtosort[i] % 2 == 0: sortedlist.append(listtosort[i]) for t in range(len(listtosort)): if listtosort[t] % 2 == 1: sortedlist.append(listtosort[t]) print(sortedlist)

You need login to submit your solution