Iterating over a collection of items to produce another collection of items is a very common task. For instance, imagine you have a list of integers and you want to create a new list containing the square of those integers. Using for loops, you could do:
numbers = [4, 5, 1, 8] squared_numbers = [] for n in numbers: squared_numbers.append(n ** 2)
While the above works, there is a much nicer way to do this in Python. It is called a comprehension and can be applied to lists, sets, tuples and dictionaries.
Let's look at implementing the example above using a list comprehension:
squared_numbers = [n ** 2 for n in numbers]
You can also filter elements out by applying a condition to the comprehension. For instance, imagine you would like to exclude all negative numbers from the list of squared numbers. You could do:
squared_numbers = [n ** 2 for n in numbers if n > 0]
Define the following list:
data = [1.9, -15.1, 4.2, 3.3, 9.0, 3.0, 10.5, 25.6, 3.5]
Use a list comprehension to create another list data_clean
which contains the values of data
which are smaller or equal to twice the mean value of data
.