This post is a quick recap on what I’ve learned about:
1. List comprehension
3. Iterable and iterator
- We can create a list in this way:
lc = [x_expression for x in iterable if condition] lc = [x_y_expression for x in iterable if condition for y in iterable if condition]
- Note that list comprehension is not a step-by-step in-place substitution. Instead, it puts together a new list by the rule and links it to our variable name “lc”.
- Likewise, we can create generators in this way:
g = (x_expression for x in iterable if condition) g = (x_y_expression for x in iterable if condition for y in iterable if condition)
- Function with
returnreturns a generator object.
When such a generator object is iterated, it runs the code between the beginning and the first
yield, the first
yieldand the second
yield, so on so forth.
Iterable and iterators
- Objects that can be iterated are iterables.
Dictionaries and generators are also iterables.
- Objects that can be iterated and support function next(iter) to find the next element are iterators.
Iterator includes generators and some customized objects.
A customized iterator must have
iter(iterable)returns its according iterator.
- The benefit of an iterator is that every element is computed when called and there no need for space to store all the elements.