Python’s zip() function

In this tutorial, we will discuss a few important things about Python’s zip() function. Here, we consider Python3.

The zip() function takes iterables (can be zero or more), aggregates them in a tuple and returns it.

The syntax of the zip() function is: zip(iterables)

At first, we create an iterator object using zip().

numbers = list(range(5)) # list of numbers 
letters = ['a', 'b', 'c', 'd', 'e'] # list of numbers
# Create an iterator object using zip()
zipped = zip(numbers, letters)
# Print the type of zipped
print('Type of zipped is: {}'.format(type(zipped)))

The output of the above print function is as follows:

Type of zipped is: <class 'zip'>

Now, we create a list of tuples from this zipped object.

# Create a list of tuples from zipped object
zipped_list = list(zipped)
# Print the list of tuples
print('List of tupples is: {}'.format(zipped_list))

The output of the above print function is as follows:

List of tupples is: [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

Parallel loop using zip()

Parallel for loop using zip() can be achieved as follows:

for num, lett in zip(numbers, letters): 
print(num, lett)

The output of the above print function is as follows:

0 a
1 b
2 c
3 d
4 e

Unzipping

A list of tuples can be unzipped using zip() with an unpacking operator *.

pairs = [(0,'x'), (1, 'y'), (2, 'z')] # list of tupples# use unpacking operator * to unzip the data
nums, alphabets = zip(*pairs)
# Print the outputs
print(nums)
print(alphabets)

The outputs of the above two print functions are as follows:

(0, 1, 2)
('x', 'y', 'z')

Note that both the outputs are tuples.

This tutorial was initially posted at http://soumenatta.blogspot.com/.

--

--

--

Postdoctoral Researcher at Laboratoire des Sciences du Numérique de Nantes (LS2N), Université de Nantes, IMT Atlantique, Nantes, France.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Git vs. GitHub

PowerShell | Most Useful Concepts And Knowledge

An Introduction into Regular Expressions

Minimal Programs

How to do Nested Joins or Intersect in MySQL

Future proof software

Kafka cluster with 3 nodes on a single machine.

Batcycle — An intro to implementing Sidecar Pattern in K8s

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dr. Soumen Atta, Ph.D.

Dr. Soumen Atta, Ph.D.

Postdoctoral Researcher at Laboratoire des Sciences du Numérique de Nantes (LS2N), Université de Nantes, IMT Atlantique, Nantes, France.

More from Medium

how to sort your package in python

Python Assert Statements — Use Cases

Python Data Model

Python: Variables and Assignments

Photo by Brookside Admin