We call up a list comprehension not because it deals with the list but because it creates a list.
Comprehensions let you skip the for loop and start creating lists, dicts, and sets straight from your iterables. Comprehensions also let you emulate functional programming aspects like map() and filter() in a more accessible way. It makes your code cleaner, smaller, and more Pythonic with lists, dicts, and sets!
Created from Iterable
Normal
nums = range(5, 101)
halves = []
for num in nums:
halves.append(num/2)
>>> halves
Comprehension
halves = [num/2 for num in range(5, 101)]
Fizz Buzz (Using If)
We can add ifs onto our comprehensions, which let us filter out things.
What is Fizz Buzz?
- Now normally in fizz buzz, you go through all the numbers from 1 to 100.
- If the number that you’re currently on is divisible by three then you print fizz.
- If it’s divisible by seven you print buzz.
- If it can be divided by both of those then you print fizz buzz.
print([num for num in range(1, 101) if num % 3 == 0])
Double Loops
Create a grid using comprehension
rows = range(4)
cols = range(10)
[(x, y) for y in rows for x in cols]
Alphanumeric list of tuples
[(letter, number) for number in range(1, 5) for letter in 'abc']