Python List Comprehensions

Page content

Python List Comprehensions is a pretty interesting feature that I haven’t seen in other languages (at least that I’ve played with). The basic idea is that they create lists from other iterables. They consists of brackets containing the expression which is executed against each item in the iterable object. One or more conditionals dictate if the item is added to the new list.

The basic format is –

list = [expression for_loop_one_or_more conditions]

Some examples-

#Let's square all the numbers
numbers = [1,2,3,4,5,6,7,8,9,10]
squares = [n**2 for n in numbers]
#squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#Let's square only the odds
numbers = [1,2,3,4,5,6,7,8,9,10]
squares = [n**2 for n in numbers if n % 2]
#squares = [1, 9, 25, 49, 81]
Carl Sampson avatar
I am an application security guy living in Indiana. I also started and lead the OWASP Indianapolis Chapter.
comments powered by Disqus