Lesson 3 ❮ Lesson List ❮ Top Page
❯ 3.5 Zip and Enumerate
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 9m 48s
☷ Interactive readings 5m
The zip(iter1,iter2,...) function takes multiple iterables (such as list, tuple, dictionary, etc.), joins them in a tuple, and returns it.
Since it cannot be printed directly, the for loop can be used here.
Since the zip object is essentially a collection of 2-tuples, it can be easily converted to dictionary using dict().
It can be annoying to use len() and range() just to get the index of a container.
enumerate(container, start=num)
gives an iterable (like zip) that contain the index and the items in the container.
It can be combined with the zip() method as well. Just like zip, it cannot be printed.
Say you have a list of tuples and want to separate the elements of each tuple into independent sequences. To do this, you can use zip() along with the unpacking operator *.
This does not work on dictionaries.
Both zip and enumerate are exhaust iterators--meaning after you unpack it once, it will become exhausted and no longer usable.
You need to explicitly convert the iterator into a list/tuple if you want to unpack it multiple times. Enclosed the zip() in Line 4 with tuple() to resolve this error.
Remember, converting iterator to tuple/list will take the program longer to run!