List comprehensions provide a more concise way of doing simple filtering and mapping. Their use is very idiomatic in Python, so you'll see them a lot. Understanding them will not only let you write better Python code, it will also help you understand other code.
Let's start with the concept of mapping. A list comprehension can be used to do the mapping we saw earlier:
a = range(20) [x**2 for x in a] #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
One thing to notice is that this results directly in a list unlike map
, whose result needs to be converted to a list. Secondly, notice how much simpler and direct the syntax is:
[function_of_variable for variable in a_list]
Compare this to:
list(map(lambda x: function_of_variable, a_list))
This is even more pronounced if we add the filter:
[variable for variable in a_list if predicate_of_variable]
Compare this to:
list(map(lambda x: function_of_variable, (filter lambda x: predicate_of_variable, a_list)))
To pick out the multiples of 3 as before we can use:
[x for x in a if x % 3 == 0] #[0, 3, 6, 9, 12, 15, 18]
As before we can combine mapping and filtering:
[x**2 for x in a if x % 3 == 0] #[0, 9, 36, 81, 144, 225, 324]
Compare this to the version using map and filter:
list(map(lambda x: x**2, filter(lambda x: x % 3 == 0, a))) #[0, 9, 36, 81, 144, 225, 324]
Text editor powered by tinymce.