Ever faced the problem of creating a unique lists in Python? or Accessing only specific elements of lists in Python? Python’s “List Comprehensions” offers you the immense power to create and use lists. Here is a brief introduction to understand and getting started on using List Comprehensions in Python.
Python’s List Comprehensions Example 1
The most simplest way in Python to create a list of integers is to use the “range” function. For example, range(10) will give you range of integers staring from 0 to 9 ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).
However, the range function has limited use, if you want to create the list of your interest, for example if you want to create list
[0,2,4,8,16,,,]
where each element is a power of 2, it does get little bit more challenging. One approach to create the list is to use the map function in combination with lambda function as
map( lambda x: 2**x, range(10))
.
This is where Python’s List comprehension comes to help us create lists like these in a concise way. The Python List comprehensions way of creating the above list is
[2**x for x in range(10)]
You can see List Comprehensions makes it easier to create lists with no need for using map and lambda functions.
Python’s List Comprehensions Example 2
Let us see one more example of List comprehension and compare it with map/lambda function route.
Let us we have a list (range(10)) and want to get the elements of certain indices ([1,3,5])from the list.
myList = range(10)
indList = [1,3,5]
One can use the functions “map and lambda” to get the elements like
map(lambda i:myList[i], indList)
The list comprehensions way to get the elements of certain indices is
[myList[i] for i in indList]