Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • What is Data Integrity? SQL
  • TypeError: ‘str’ object is not callable Python Functions
  • How to Pass Python Variables to Javascript Javascript
  • Python tutorial: Pandas groupby ( Video 1) Python
  • Deleting table records with SQL SQL
  • How to import data into excel Python Tutorial
  • What is The Julia Programming Language Julia programming
  • How To Validate Cell Values In Excel Python

How to use zip() function in Python

Posted on February 15, 2023February 15, 2023 By admin

Estimated reading time: 3 minutes

Sometimes you need a function that will help you to aggregate or combine severable iterables in one go.

When we read the official Python documentation it states that using zip ” Iterates over several iterables in parallel, producing tuples with an item from each one.”

So what does that actually mean?

Well in essence essentially what it means is that if you want to combine two sets of data so that they sit side by side in the order they are in, using zip will help you to achieve this.

Let’s look at an example. In the below code, we use zip in a loop.

As can be seen, it is looping over two different lists and then combining them into three separate tuples:

for item in zip([1, 2, 3], ['Liverpool', 'Manchester Utd', 'Manchester City']):
    print(item)
    print(type(item))

The output of the above code shows:

(1, 'Liverpool')
<class 'tuple'>
(2, 'Manchester Utd')
<class 'tuple'>
(3, 'Manchester City')
<class 'tuple'>

As can be seen, the output is three different tuples.

Does zip default to tuples when giving output?

Yes, it does by default, but there are other ways to achieve a different output. For example, if you would like to use list comprehension to obtain a set of lists, you would do the following:

y = [list(x) for x  in zip([1,2,3], ['Liverpool', 'Manchester Utd','Manchester City'])]
print(y)
print(type(y))

Giving the following output:

[[1, 'Liverpool'], [2, 'Manchester Utd'], [3, 'Manchester City']]
<class 'list'>

Does the zip function need to be processed before it gives an output?

Yes, it does, the design of the zip function determines that it is lazy, as a result, if you do not use a loop on it or wrap it within a list for example, it will not give the output you desire.

If the below is run:

a = [1,2]
b =['j','k']

c= zip(a,b)
print(c)
print(type(c))

It gives this output:

<zip object at 0x000001330E1E8D40>
<class 'zip'>

On the other hand, if you use a list for example, the output will be a list as follows:

a = [1,2]
b =['j','k']

c= list(zip(a,b))
print(c)
print(type(c))

Giving you:

[(1, 'j'), (2, 'k')]
<class 'list'>

Can I unzip a set of data?

Python does not have a function to unzip, but they have provided the functionality as follows.

It is pretty simple to unzip, as you can see we have put an asterisk beside “d” below, which is what Python recognizes to perform an unzip operation.

a = [1,2]
b =['j','k']

c= list(zip(a,b))
print(c)
print(type(c))

d,f = zip(*c)
print(d,f)

And the result is, output in a tuple:

[(1, 'j'), (2, 'k')]
<class 'list'>
(1, 2) ('j', 'k')

What happens if the iterators are of different lengths?

Essentially the code will complete without error, but will only return output based on the iterator with the least amount of values in it.

For example in the below, a,b are the iterators, but as b has only got two values in it, only two values are returned in the output:

a = [1,2,3,4]
b =['j','k']

c= list(zip(a,b))
print(c)
print(type(c))

Which gives the following. Notice that the first two items of iterator A are joined with the two items of iterator b.

[(1, 'j'), (2, 'k')]
<class 'list'>

Can I enumerate using the zip function?

The zip function is very versatile and you can enumerate, the following is an example:

country = ['Ireland', 'England', 'Wales']
capital = ['Dublin', 'London', 'Cardiff']

for i, (country, capital) in enumerate(zip(country, capital)):
    print(i, country, capital)

This has the effect of giving the following output:

0 Ireland Dublin
1 England London
2 Wales Cardiff

What are some use of the Zip function?

  1. Creating comparisons – If you have two lists for example it can be used to compare the two and then show the differences.
  2. It can also be used to pair data, and perform operations on those paired data.
  3. You could use it to sort lists based on values in one list that is in a particular position of another list.
Python, Python Functions, Python Lists, Python Tuples Tags:Python, python loop, python tuples, Tuples, unzip function

Post navigation

Previous Post: How to pass by reference or pass by value in Python
Next Post: TypeError: not all arguments converted during string formatting

Related Posts

  • How To Check For Unwanted Characters Using Loops With Python Python Data Cleansing
  • How To Pass Data Between Functions Python Functions
  • TypeError: ‘float’ object is not callable Python
  • How to Generate Random Integers Between 0 and 9 Python
  • How many python functions are there? Python
  • How To Add Values to a Python Dictionary Python

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • Deutsch
  • What Are Constraints in SQL? SQL
  • how do I merge two dictionaries in Python? Python
  • Why choose Julia over other programming languages? Julia programming
  • How To Validate Cell Values In Excel Python
  • YouTube channel lists – Python working with files Python working with files
  • How to Pass Python Variables to Javascript Javascript
  • What are Lambda functions in Python? Python
  • Import a CSV file with an SQL query CSV

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT