Question 6.11: Applying a Function to a List You need to apply a function t......

Applying a Function to a List

You need to apply a function to each element of a list and collect the results.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...