Python Practice › List Programs › Program 10

Odd values left, even values right

EasyList Programs · 10 of 100

Write a Python program to rearrange a list so all odd values come first and all even values after them, keeping their order.

Advertisement
Input
[5, 7, 2, 8, 11, 12, 17, 19, 22]
Output
[5, 7, 11, 17, 19, 2, 8, 12, 22]

Approach

  1. Join a list of the odd values with a list of the even values.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment