Using lists, dicts, and sets
A Python sequence object, such as a list
, is iterable. However, it has some additional features. We'll think of it as a materialized iterable. We've used the tuple()
function in several examples to collect the output of a generator expression or generator function into a single tuple
object. We can also materialize a sequence to create a list
object.
In Python, a list display, or list comprehension, offers simple syntax to materialize a generator: we just add the []
brackets. This is ubiquitous to the point where the distinction between generator expression and list comprehension is lost. We need to disentangle the idea of generator expression from a list display that uses a generator expression.
The following is an example to enumerate the cases:
>>> range(10)
range(0, 10)
>>> [range(10)]
[range(0, 10)]
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The first example...