Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 3    ❮    Lesson List    ❮    Top Page

3.1 Tuples  

3.2 Sets  

3.3 Dictionaries  

3.4 Looping in Dictionaries

❯  3.5  Zip and Enumerate  

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   9m 48s
☷  Interactive readings   5m

Pairing Two Iterables using zip()

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. 

Converting Zip to Dictionary

Since the zip object is essentially a collection of 2-tuples, it can be easily converted to dictionary using dict().

Getting the index using enumerate()

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.

Unzipping an Object

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.

LEARN FROM ERRORS
Problem when Unpacking zip/enumerate Multiple Times

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!

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse