Anusha Murali

Logo

Please see github.com/anusha-murali for all of my repositories.

View GitHub Profile

The zip() Function in Python

The zip() is one of the most useful functions in Python. It takes iterables such as lists and aggregate them into a tuple.

The syntax of the zip() function is,

zip(*iterables)

where the iterables can be one of the built-in iterables such as list, string, dict or any user-defined iterables.

Example 1

courses = ["CS124", "CS50", "CS182"]
scores = [94, 97, 91]

course_table = zip(courses, scores)

The result returned by zip() is an object. We can use list() to print the zip object:

print(list(course_table))
[('CS124', 94), ('CS50', 97), ('CS182', 91)]

We can also recover the original values used in the above example using zip() as shown below.

Example 2

courses, scores = zip(*course_table)

Following shows the contents of courses and scores:

print("courses = ", courses)
print("scores = ", scores)
courses =  ('CS124', 'CS50', 'CS182')
scores =  (94, 97, 91)

Example 3: Transposing a matrix using the zip() function

Let us consider the following $3 \times 3$ matrix, grid = [[3,2,1],[1,7,6],[2,7,7]].

\[\begin{bmatrix} 3 & 2 & 1 \\ 1 & 7 & 6 \\ 2 & 7 & 7 \end{bmatrix}\]

We can find its transpose easily using the zip() function as shown below:

grid = [[3,2,1],[1,7,6],[2,7,7]]
transpose = list(map(list, zip(*grid)))

Explanation:

We can print transpose and confirm:

print(transpose)
[[3, 1, 2], [2, 7, 7], [1, 6, 7]]

The above list of lists represents the transposed matrix below:

\[\begin{bmatrix} 3 & 1 & 2 \\ 2 & 7 & 7 \\ 1 & 6 & 7 \end{bmatrix}\]

Note that transpose = list(map(list, zip(*grid))) can also be written more elegantly using list comprehension with transpose = [list(i) for i in zip(*grid)].

Please see an example use case of the zip() function in Equal Row and Column Pairs hash map problem.


anusha-murali.github.io