Python List Comprehensions

List comprehensions are a concise way to create lists in Python, with a performance edge over using a list's append() method within a for loop. It's similar to writing a for loop except the expression, which normally sits inside the for loop code block, is placed ahead of the for statement and surrounded with square brackets. Here's an example:

word = 'hello'

# Normal for loop to create a list
letters = []
for char in word:
    letters.append(char)

# Create a list using a list comprehension
letters = [ char for char in word ]

This flow might seem strange initially if you're used to for loops but once you've become familiar with it, it becomes very convenient to use when you find an opportunity to.

You can also use expressions and if statements within list comprehensions. Here are a few more examples.

numbers = [1, 2, 3, 4, 5, 6]

doubled = [ n*2 for n in numbers ]
print(doubled)
# [2, 4, 6, 8, 10, 12]

evens = [ n for n in numbers if n in doubled ]
print(evens)
# [2, 4, 6]