Applying a Function to a List
You need to apply a function to each element of a list and collect the results.
Use the Python language feature called comprehensions.
The following example will convert each string element of the list to uppercase and return a new list the same length as the old one, but with all the strings in uppercase:
>>> l = [“abc”, “def”, “ghi”, “ijk”] >>> [x.upper() for x in l] [‘ABC’, ‘DEF’, ‘GHI’, ‘IJK’] |
Although it can get confusing, there is no reason why you can’t combine these kinds of statements, nesting one comprehension inside another.
Discussion
This is a very concise way of doing comprehensions. The whole expression has to be enclosed in brackets ([]). The first element of the comprehension is the code to be evaluated for each element of the list. The rest of the comprehension looks rather like a normal list iteration command (Recipe 6.7). The loop variable follows the for keyword and then after the in keyword is the list to be used.
See Also
All the recipes between Recipes 6.1 and 6.11 involve the use of lists.