Page 191 -
P. 191
comprehending data
Comprehending lists
Consider what you need to do when you transform one list into another. Four
things have to happen. You need to:
1 Create a new list to hold the transformed data.
2 Iterate each data item in the original list.
3 With each iteration, perform the transformation.
4 Append the transformed data to the new list.
1. Create.
clean_mikey = [] 2. Iterate.
for each_t in mikey: 3. Transform.
clean_mikey.append(sanitize(each_t))
4. Append.
You get to pick the target
Here’s the same functionality as a list comprehension, which involves
creating a new list by specifying the transformation that is to be applied to each identifier to use (just like with
regular iterations).
of the data items within an existing list.
clean_mikey = [sanitize(each_t) for each_t in mikey]
The new list is created… …by applying a …to each …within an existing list.
transformation… data item…
What’s interesting is that the transformation has been reduced to a single line
of code. Additionally, there’s no need to specify the use of the append()
method as this action is implied within the list comprehension. Neat, eh?
you are here 4 155