7 Levels of Using the Zip Function in Python
- Level 0: Basics of using the zip function
- Level 1: Connecting fewer or more elements
- Level 2: Working with Arguments of Unequal Lengths
- Level 3: Unpacking Operation
- Level 4: Creating and Updating Dictionaries with the zip Function
- Level 5: Using the zip Function in For Loops
- Level 6: Matrix Transpose
- Conclusion
Programming skills are a quality that distinguishes one candidate from another during an interview. That’s why we pay close attention to this question. The elegance of constructions and the conciseness and succinctness of code demonstrate a programmer’s skill and experience.
On 365educating articles, we’ve already covered numerous examples of how to improve your Python code, how to work with strings in Python, reviewed basic library functions, and much more. Today, we’ll dedicate an entire article to a lesser-known but very useful function: zip.
A function
zipis a function in Python that combines elements from different iterables, such as lists, tuples, or sets, and returns an iterator.
This feature can make code very elegant. However, its use is not very intuitive for beginners and sometimes leads to errors.
For example, we have a matrix 2*3represented by a nested list:
matrix = [[1, 2, 3], [1, 2, 3]] Here’s a popular Python interview question:
How to get the transpose of the above matrix?
A Junior developer might write several for loops to implement it, but a Senior developer only needs one line of code:
matrix_T = [list(i) for I in zip(*matrix)] Elegant, isn’t it?
If you haven’t figured out the solution above yet, don’t worry. This article will explain the concepts and usage of this powerful function in detail zip. If you’re already familiar with this approach but want to learn more amazing tricks with the function zip, this article is for you.
Level 0: Basics of using the zip function
The function zipCombines elements from different iterables, such as lists, tuples, or sets, and returns an iterator.
For example, we can use it to concatenate two lists like this:
id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
record = zip(id, leaders)
print(record)
# zip object at 0x7f266a707d80
print(list(record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')] As shown in the example above, the function zipreturns an iterator of tuples, where the i-th tuple contains the i-th element of each of the lists.
It looks like the zipper on your jacket works, doesn’t it?
Level 1: Connecting fewer or more elements
In fact, zipPython’s zipper function is much more powerful than a physical zipper. It can operate on any number of iterables simultaneously, not just two.
If we pass a single list to the zip function:
id = [1, 2, 3, 4]
record = zip(id)
print(list(record))
# [(1,), (2,), (3,), (4,)] How about three lists?
id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
sex = ['male', 'male', 'male', 'male']
record = zip(id, leaders, sex)
print(list(record))
# [(1, 'Elon Mask', 'male'), (2, 'Tim Cook', 'male'), (3, 'Bill Gates', 'male'), (4, 'Yang Zhou', 'male')] As stated above, no matter how many iterable objects we pass to the function zip, it works as expected.
By the way, if there is no argument, the zip function simply returns an empty iterator.
Level 2: Working with Arguments of Unequal Lengths
Real data isn’t always clean and complete; sometimes we have to process iterables of unequal length. By default, the function’s result zipdepends on the shortest object.
id = [1, 2]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
record = zip(id, leaders)
print(list(record))
# [(1, 'Elon Mask'), (2, 'Tim Cook')] As shown in the code above, idis the shortest list, so recordit contains only two tuples, and the last two leaders in the list leadershave been skipped.
What if the last two leaders are unhappy about being ignored? Python can help us again. The module itertoolscontains another function, zip_longest. As the name suggests, it’s a sibling of zip, and its result depends on the longest argument.
Let’s use zip_longest to create a list of records:
from itertools import zip_longest
id = [1, 2] leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
long_record = zip_longest(id, leaders)
print(list(long_record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (None, 'Bill Gates'), (None, 'Yang Zhou')]
long_record_2 = zip_longest(id, leaders, fillvalue='Top')
print(list(long_record_2))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), ('Top', 'Bill Gates'), ('Top', 'Yang Zhou')] Now neither Bill Gates nor Yang Zhou will be upset. The optional argument fillvaluecan help us fill in the missing values. The argument’s default value is None, But we can put anything we want there! It’s still unclear what would be more frustrating: not being included in the list recordor getting something like that next to our name.
Level 3: Unpacking Operation
In the previous example, if we first get a list record, how can we unzip it into individual objects?
Unfortunately, Python doesn’t have an unzip function. However, if you’re familiar with asterisk tricks, unzipping is a very simple task.
record = [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')]
id, leaders = zip(*record)
print(id)
# (1, 2, 3, 4)
print(leaders)
# ('Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou') In the example above, asterisk performed the unpacking operation on all four tuples from the list record.
If we don’t use the asterisk method, the following method will be identical:
record = [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')]
print(*record) # unpack the list by one asterisk
# (1, 'Elon Mask') (2, 'Tim Cook') (3, 'Bill Gates') (4, 'Yang Zhou')
id, leaders = zip((1, ‘Elon Mask’), (2, ‘Tim Cook’), (3, ‘Bill Gates’), (4, ‘Yang Zhou’))
print(id)
# (1, 2, 3, 4)
print(leaders)
# ('Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou') Level 4: Creating and Updating Dictionaries with the zip Function
This function zipmakes it very easy to create or update dictionaries based on individual lists. There are two one-line solutions:
- Use
dict comprehensionandzip - Using the function
dictandzip
id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
# create dict by dict comprehension
leader_dict = {i: name for i, name in zip(id, leaders)}
print(leader_dict)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou'}
# create dict by dict function
leader_dict_2 = dict(zip(id, leaders))
print(leader_dict_2)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou'}
# update
other_id = [5, 6]
other_leaders = ['Larry Page', 'Sergey Brin']
leader_dict.update(zip(other_id, other_leaders))
print(leader_dict)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou', 5: 'Larry Page', 6: 'Sergey Brin'} The example above doesn’t use for loops at all. How elegant!
Level 5: Using the zip Function in For Loops
This is a common scenario when multiple iterables are being processed concurrently.
Let us illustrate this with the following example:
products = ["cherry", "strawberry", "banana"]
price = [2.5, 3, 5]
cost = [1, 1.5, 2]
for prod, p, c in zip(products, price, cost):
print(f'The profit of a box of {prod} is £{p-c}!')
# The profit of a box of cherry is £1.5!
# The profit of a box of strawberry is £1.5!
# The profit of a box of banana is £3! Is there a neater way to implement the example above? Hardly.
Level 6: Matrix Transpose
Finally, we return to the Python interview question:
How to get the transpose of a matrix?
Since we are already familiar with the function zip, unpacking with a single asterisk, and dict comprehensionThe one-line solution becomes intuitive:
matrix = [[1, 2, 3], [1, 2, 3]]
matrix_T = [list(i) for i in zip(*matrix)]
print(matrix_T)
# [[1, 1], [2, 2], [3, 3]] Conclusion
The function zipis very useful and powerful in Python. Using it correctly can help us write less code and perform more operations.
It’s not for nothing that “Do more with less” is the Python philosophy.
Explore More IT Terms
#
A
- A Guide to SQL Query Formatting
- A/B testing
- Agile
- Algorithm complexity in 5 minutes
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data structures
- Defining Aliases
- Defining Arrays
- Deque
- Developing a Website from Scratch
- Digital data: understand the importance of this asset for businesses.
- Doubly linked lists
E
F
H
- Handling errors and exceptions
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Inserting an Image
- Interactive Python Tutorial – Learn Programming from Scratch
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to programming languages
- IT Specialist Resume (CV)
K
M
P
S
- SFML Graphics Library Tutorials
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Statistical analysis: importance for decision making.
- String formatting in Python
- Swift Lessons
- switch/match construct
T
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a GPU in a computer, in simple terms?
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview
