Summary
In this lesson, you learned that:
- A list comprehension builds a new list from another one in a single line:
[score * 2 for score in scores]. First comes what goes into the new list, then theforpart, the first line of a loop without its colon. It does what an empty list, a loop and.append()do. - An
ifat the end picks elements:[score for score in scores if score >= 50]keeps only the scores of 50 or more. It goes after theforpart, without a colon. - The first part can call a method or a function on each element:
[name.strip() for name in names],[len(word) for word in words]. Call it on the element, not on the list. - The
forpart goes through anything a loop can: a list,range(), or pairs with two variables:[name for name, points in results if points >= 100]. - The result is a new list, and the original stays as it was. You can store the new list, print it or pass it straight to
sum(),len(),max()orsorted():sum([len(word) for word in words]). - A dictionary comprehension is written in curly braces, with a key, a colon and a value first:
{name: len(name) for name in names}. To make one from another dictionary, go through.items():{item: price for item, price in menu.items() if price < 50}. - Curly braces without a colon make a set comprehension, which gives a set with each value only once:
{vote.lower() for vote in votes}.
A comprehension isn't always the better choice. Use it when you make a new list (or a dictionary, or a set) and it reads well on one line. A plain loop is clearer when each element needs several steps, or when the point is to print something rather than to make a list. [print(name) for name in names] does print the names, but it also makes a list that nobody needs: a None for each print(). And if you have to read a comprehension twice to understand it, write the loop.
Next comes another small project: a leaderboard for a game, put together from the results the game saved. Then, in the lesson on errors and exceptions, you will learn to catch errors, so that a program can go on even when, for example, a text that should be a number isn't one.
Instructions
- 1
Let's practice. In an online quiz, the players answered the question “What is the capital of France?”, and the list
answersholds what they typed. Count the right answers, whatever their spaces and capital letters: with a list comprehension, pick the answers that are"paris"once they are stripped and lowercased, and print how many there are withlen():Right answers: 3. Keep the line withanswersas it is: the exercise also checks your program with other answers. - 2
Below, print the different answers, each only once, cleaned up the same way and in alphabetical order:
sorted()of a set comprehension. The output is['london', 'paris', 'rome'].