List comprehension are one of my favourite pieces of Python syntax. We can use a list comprehension to create a list from another iterable. It's fast, Pythonic, and best of all, easy to read.

When working with code, it's quite common for us to run into a pattern like this:

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

for number in numbers:
	doubled_numbers.append(number * 2)

This method is perfectly functional, but compare it to the list comprehension version:

numbers = [1, 2, 3, 4, 5]
doubled_numbers = [number * 2 for number in numbers]

Not only is the code more succinct, we've actually made it more readable as well. A vast improvement!

List comprehensions also allow for more than one for clause. We can use this to find all the possible combinations of dice rolls for two dice, for example:

roll_combinations = [(d1, d2) for d1 in range(1, 7) for d2 in range(1, 7)]

Not bad for a one-liner!

You can find out more about list comprehensions in the official documentation.

If you want to learn more cool tricks like this, be sure to check out our Complete Python Course, which you can get for just $9.99 by following the link in this post. We'd love to have you.