3.5 Comprehensions
We have seen two ways of making a copy of a list. The first is to use the aptly named copy method.
brands = ["Fender", "Gibson", "Ibanez"]
brands.copy()
['Fender', 'Gibson', 'Ibanez']
The second technique is copying via slicing.
brands[:]
['Fender', 'Gibson', 'Ibanez']
We now look at a third technique that generalizes well beyond copying.
[brand for brand in brands]
['Fender', 'Gibson', 'Ibanez']
This is a list comprehension, and this is an elementary example of it. It is a simpler way of building the list than with a full loop and append.
brands_copy = []
for brand in brands:
brands_copy.append(brand)
brands_copy
['Fender', 'Gibson', 'Ibanez']
Let’s add a filter in the form of a conditional and create a new...