Five Examples of Using List Comprehensions in Python

List Comprehensions in Python are awesome. A while back wrote a post on some examples of using List Comprehensions in Python. Here are more examples of List Comprehensions

1. Converting a list of integers to a list of strings

Let us say we have a list of integers like

>>>my_list = [0,1,2,3,4,5]

and we can use List Comprehensions

>>>[str(x) for x in my_list]

to get a list of strings

['0', '1', '2', '3', '4', '5']

2. Looping or iterating through two lists with List Comprehension

Let us say we have two lists “my_list1” and “my_list2”

>>>my_list1 =[0,1]
>>>my_list1 =['zero','one']

We can use List comprehensions to loop through each list and write out tuples of the elements.

>>>[(x,y) for x in my_list1 for y in my_list2]

and get the list of tuples.

[(0, 'zero'), (0, 'one'), (1, 'zero'), (1, 'one')]

3. Getting index of each element of list with enumerate and List Comprehensions

We can use List comprehensions and enumerate in python to get index of each element in a list. Let us say we have list

>>>my_list= ['a','b','c','d','e']

Python’s built-in function ‘enumerate’ lets us to loop over a list and get both the index and the value of each item in the list. We can combine enumerate with List comprehensions to get a index and element tuple.

>>>[(i,j) for (i,j) in enumerate(my_list)]

we get

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

4. Using if statement in List Comprehensions

We can use if statement in list comprehension. For example, to get index of a specific element in a list, we can use

>>>[i for (i,j) in enumerate(my_list) if j=='c']

we will get

[2]

5. Using if-else statement in List Comprehensions

Let us say we have a list of integers.

>>>my_list = range(10)
>>>my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We will use if-else condition within List Comprehension to get a list of strings telling us whether each element is an odd or even number.

>>>["even" if i%2==0 else "odd" for i in my_list]
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']