List Comprehensions

A list comprehension builds a new list from the values of a list, or of anything else you can loop over. It does this in one expression.

words = ["sun", "moon", "star"]

upper = [word.upper() for word in words]
lengths = [len(word) for word in words]

print(upper)
print(lengths)

Output:

['SUN', 'MOON', 'STAR']
[3, 4, 4]

Read the first one like this: for each word in words, make word.upper(), and collect all the results in a new list.

Use a comprehension when you need a new list and the change to each value is simple. A normal loop is better when the loop does other work, such as printing, or when the expression gets hard to read.

In the exercise, build the two lists the task asks for.