List Comprehensions in Python are awesome. List Comprehensions lets your create lists without actually writing a for loop. A while back wrote a post on some examples of using List Comprehensions in Python. Here are 5 more examples of List Comprehensions, that will come in extremely handy whenever you deal with lists in Python.
1. How to Convert 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. How to get tuples from two lists with List Comprehensions?
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. How to Get Index of Each Element of List with enumerate and List Comprehensions
Often you may need to have access to get index of each element in a list. 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. How to Use if Statement in List Comprehensions?
In the earlier example, we saw how to use enumerate and list comprehensions to index of each element in a list. Suppose, if we want index of a specific element, we can use if statement in list comprehension to check for specific element and get its (or their) index. For example, to get index of a specific element ‘c’ in a list, we can use
>[i for (i,j) in enumerate(my_list) if j=='c']
we will get
[2]
5. How to Use 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']