Methods and Functions Inside
The first part of a list comprehension doesn't have to be a calculation. It can be anything you could pass to .append(), and very often it's a method or a function called on each element. Names that people type into a form often have spaces around them, and .strip() removes them:
names = [" Anna", "Tom ", " Eva "]
clean = [name.strip() for name in names]
print(clean)['Anna', 'Tom', 'Eva']For each name, Python calls name.strip() and puts the text it returns into the new list. You can chain methods here too: name.strip().lower().
A function works the same way. len() turns a list of words into a list of their lengths:
words = ["sun", "banana", "kiwi"]
lengths = [len(word) for word in words]
print(lengths)[3, 6, 4]The for part can go through anything a for loop can, range() too. These are the squares of the numbers from 1 to 5:
squares = [n * n for n in range(1, 6)]
print(squares)[1, 4, 9, 16, 25]And because a list comprehension gives you a list, you can pass it straight to anything that takes a list, such as sum(), max(), sorted() or ", ".join(). This adds up the lengths of all the words, without a variable for the list of lengths:
words = ["sun", "banana", "kiwi"]
print(sum([len(word) for word in words]))13Python first builds the list [3, 6, 4], and sum() then adds it up.
A typical mistake is to call the method on the list instead of on its element: [names.strip() for name in names]. A list has no method strip(), only a text has one, so the program ends with AttributeError: 'list' object has no attribute 'strip'. Call the method on the element: name.strip().
Instructions
- 1
The players typed their words carelessly, with spaces and capital letters. Make a list
cleanwith a list comprehension: each word without the spaces around it and in lowercase letters. Print it:['pizza', 'cat', 'robot', 'sun']. Keep the line withwordsas it is: the exercise also checks your program with other words. - 2
Each letter scores one point. Print the points for the whole round:
sum()of a list comprehension with the lengths of the clean words. The output isPoints: 16.