Python Practice › List Programs › Program 10
Odd values left, even values right
Write a Python program to rearrange a list so all odd values come first and all even values after them, keeping their order.
Input
[5, 7, 2, 8, 11, 12, 17, 19, 22]
Output
[5, 7, 11, 17, 19, 2, 8, 12, 22]
Approach
- Join a list of the odd values with a list of the even values.
Solution
numbers = [5, 7, 2, 8, 11, 12, 17, 19, 22]odds = [n for n in numbers if n % 2]evens = [n for n in numbers if n % 2 == 0]print(odds + evens)Output
[5, 7, 11, 17, 19, 2, 8, 12, 22]
Line by line
Line 2
n % 2 is 1 (truthy) for odd numbers.
Learn the concept
New to this topic? Read the lesson, then come back.