Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python print() function
Next article icon

zip() in Python

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The zip() function in Python combines multiple iterables such as lists, tuples, strings, dict etc, into a single iterator of tuples. Each tuple contains elements from the input iterables that are at the same position.

Let’s consider an example where we need to pair student names with their test scores:

Python
names = ['John', 'Alice', 'Bob', 'Lucy'] scores = [85, 90, 78, 92]  res = zip(names, scores) print(list(res)) 

Output
[('John', 85), ('Alice', 90), ('Bob', 78), ('Lucy', 92)] 

Explanation:

  • zip() is used to combine the two lists into a single iterable ‘res‘
  • Each element from names is paired with the corresponding element from scores
  • list() converts the iterator from zip() into a list of tuples, making it easier to visualize or manipulate the combined data.

Table of Content

  • Syntax of zip()
  • Examples of zip()
    • Iterables of different Lengths
    • Unzipping data with zip()
    • Combine dictionary keys and values

Syntax of zip()

zip(*iterables) 

Parameters:

*iterables refers to one or more iterable objects (like lists, tuples, etc.) that we want to combine. The function pairs elements from these iterables into tuples based on their positions.

Return value:

Returns an iterator of tuples, where each tuple contains elements from the input iterables at the same index. If the input iterables are of unequal length then zip() stops creating tuples when the shortest iterable is exhausted.

Key Points:

  • If no parameters are passed, zip() returns an empty iterator.
  • If only one iterable is passed, the result will be a series of single-element tuples.
  • If multiple iterables are passed, each tuple will contain one element from each iterable.

Examples of zip()

Below example shows how zip() works when no parameter, one and two iterable are passed into parameter.

Python
a = [1, 2, 3] b = ['a', 'b', 'c']  # No iterable are passed res = zip()  # Converting iterator to list print(list(res))  # One iterable is passed res = zip(a)  # Converting iterator to list print(list(res))  # Two iterables are passed res = zip(a, b)  # Converting iterator to list print(list(res)) 

Output
[] [(1,), (2,), (3,)] [(1, 'a'), (2, 'b'), (3, 'c')] 

Iterables of different Lengths

When using iterables of different lengths, the zip() will only pair up to the shortest iterable.

Python
names = ['Alice', 'Bob', 'Charlie'] scores = [88, 94]    res = zip(names, scores) print(list(res)) 

Output
[('Alice', 88), ('Bob', 94)] 

Explanation: Here, zip() stops after pairing the two available score values with the first two name values. ‘Charlie’ is left out since there’s no corresponding score value.

Unzipping data with zip()

We can also reverse the operation by unzipping the data using the * operator. Let’s see how that works:

Python
a = [('Apple', 10), ('Banana', 20), ('Orange', 30)]  fruits, quantities = zip(*a)  print(f"Fruits: {fruits}") print(f"Quantities: {quantities}") 

Output
Fruits: ('Apple', 'Banana', 'Orange') Quantities: (10, 20, 30) 

Explanation: Using the * operator, we can separates (unzip) the paired fruit names and their quantities back into their respective sequences

Combine dictionary keys and values

We can use zip() to combine dictionary keys and values, or even iterate over multiple dictionaries simultaneously. Here’s an example pairing dictionary keys and values.

Python
d = {'name': 'Alice', 'age': 25, 'grade': 'A'}  keys = d.keys() values = d.values()  res = zip(keys, values) print(list(res)) 

Output
[('name', 'Alice'), ('age', 25), ('grade', 'A')] 

Related Articles:

  • Use enumerate() and zip() together in Python
  • Zip Different Sized List in Python
  • How to Zip two lists of lists in Python?
  • Zip Uneven Tuple in Python
  • Ways to Sort a Zipped List by Values in Python


Next Article
Python print() function
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python-Built-in-functions
  • python-list
  • python-list-functions
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python next() method
    Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. C/C++ Code l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2. It has been replaced
    4 min read
  • Python oct() Function
    Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
    2 min read
  • ord() function in Python
    Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language. Unicode includes: ASCII characters (first 128 code points)Emojis, currency symbols, accented characters, etc.For example, unicode of
    2 min read
  • pow() Function - Python
    pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example: [GFGTABS] Python print(pow(3,2)) [/GFGTABS]Output9 Explanation: pow(3, 2) calculates 32 = 9, where the
    2 min read
  • Python print() function
    The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
    2 min read
  • Python range() function
    The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. [GFGTABS] Python for i in range(5): print(i, end="
    7 min read
  • Python reversed() Method
    reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example: [GFGTABS] Python a = ["nano",
    4 min read
  • round() function in Python
    Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
    6 min read
  • Python slice() function
    In this article, we will learn about the Python slice() function with the help of multiple examples. Example C/C++ Code String = 'Hello World' slice_obj = slice(5,11) print(String[slice_obj]) Output: World A sequence of objects of any type (string, bytes, tuple, list, or range) or the object which i
    5 min read
  • Python sorted() Function
    sorted() function returns a new sorted list from the elements of any iterable like (e.g., list, tuples, strings ). It creates and returns a new sorted list and leaves the original iterable unchanged. Let's start with a basic example of sorting a list of numbers using the sorted() function. [GFGTABS]
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences