List comprehensions, explained simply
Often you make a new list by looping over another list and appending something each time. A list comprehension does all of that in one line.
Read [n * 2 for n in numbers] as "n times two, for every n in numbers". The square brackets tell Python the result is a list.
You can add an if at the end to keep only some items: [n for n in numbers if n > 3]. Comprehensions are neat, but a normal loop is fine when the logic gets complicated.
Example: Make patterns quickly
sizes = [1, 2, 3, 4]
rows = ["*" * s for s in sizes]
print(rows)
print([s for s in sizes if s % 2 == 0])Output
['*', '**', '***', '****']
[2, 4]Try this
- Make a list of the squares of the numbers 1 to 10.
- Turn a list of names into capital letters with .upper() in a comprehension.
- Write the same thing as a normal for loop and compare the two.
