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.
Wrapping Up
If you want to learn more cool tricks like this, be sure to check out our Complete Python Course, and come join us over on our Discord server. We'd love to have you!
If you're interested in more content like this, be sure to sign up to our mailing list below. Not only is it a great way to stay up to date with our content, we also regularly post discount codes for our subscribers, ensuring they get the best price available for our courses.