List comprehensions
A list comprehension is a way to create a new Python list from any iterable structure (often another list, but not necessarily). The syntax looks a lot like the construction of a list with known components.
where if boolean is optional.
Here are a couple of examples.
First, we create a list from a range
Why would we want to do this? Python ranges are different than lists; in particular, while they are iterable, they are not mutable.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/tmp/ipykernel_759/2580088131.py in <module>
2 print(r)
3 print(type(r))
----> 4 r.append(10)
AttributeError: 'range' object has no attribute 'append'
Next, let's compute the squares of the first 10 positive integers.
Now, let's use a list comprehension to write a function that takes any iterable object as its first argument, and returns a list of the values in that first argument that are divisible by the second argument.
And now let's see if it works!
It's not just numbers that we can process using list comprehensions. The following set of examples come from this site. First we define a string to operate on.
Now let's write a list comprehension that finds the length of each of the words
Figure out the longest word in the sentence
How many spaces are there in string?
It's impressive what we can read without vowels. What does string look like without the vowels?
Find all of the words in string that are less than 5 letters
Write this as a function, and call it to get the same result as above.
Suppose there was no list comprehension in Python. How could we write it as a function ourselves?
Try it out a few times.
Finally, what if we give some default arguments for expression_function and contains_function.
Try it out a few times.