Python zip() Function with Examples
The zip() function in Python is a built-in function that allows you to combine two or more iterables into a single iterable object. It takes two or more iterables (e.g., lists, tuples, or strings) and returns a zip object that contains tuples, where the i-th tuple contains the i-th element from each of the input iterables. The length of the output zip object is determined by the length of the shortest input iterable.
Syntax:
The zip() function can accept any number of iterables as arguments, separated by commas, and returns a zip object.
Combining two lists using zip()
In the above example, two lists numbers and colors. Pass these two lists to the zip() function to create a zip object. Then convert the zip object to a list using the list() function and print it. The output shows that each tuple contains an element from the numbers list and an element from the colors list.
Combining three lists using zip()
In the above example, three lists list1, list2, and list3. Pass these three lists to the zip() function to create a zip object. Then convert the zip object to a list using the list() function and print it. The output shows that each tuple contains an element from the list1, an element from the list2, and an element from the list3.
Using zip() to unzip a list of tuples
In the above example, a list of tuples zipped_list. Use the zip() function with the * operator to unzip the list of tuples into two separate lists numbers and colors. Then print the two lists. The output shows that the numbers list contains the first elements of each tuple, and the colors list contains the second elements of each tuple.
Following are some examples of using the zip() function with iterables other than lists.
Zip two Strings
In the above example, create two strings string1 and string2 and use the zip() function to create an iterator that produces tuples containing the corresponding characters of the two strings. Then loop over the iterator and print each tuple.
Zip a range Object and a String
In the above example, create a range object numbers containing the numbers 1 to 4, and a string string containing the letters 'Python'. Use the zip() function to create an iterator that produces tuples containing the corresponding elements of the two iterables. Then loop over the iterator and print each tuple.
Zip two tuples
In the above example, create two tuples tuple1 and tuple2 and use the zip() function to create an iterator that produces tuples containing the corresponding elements of the two tuples. Then loop over the iterator and print each tuple.
Zip two dictionaries with different keys
In the above example, create two dictionaries dict1 and dict2 with different keys, and use the zip() function to create an iterator that produces tuples containing the corresponding values of the two dictionaries based on the keys of the first dictionary. Since the keys of dict2 do not match the keys of dict1, the values of dict2 are matched with the keys of dict1 in order.
Zip three dictionaries
In this example, create three dictionaries dict1, dict2, and dict3 with the same keys, and use the zip() function to create an iterator that produces tuples containing the corresponding values of the three dictionaries. Then loop over the iterator and print each tuple.
What are the practical uses of Python Zip?
The zip() function in Python is a versatile tool for working with iterables. Here are some practical use cases for the zip() function:
- Pairing items in two or more lists - You can use the zip() function to pair items in two or more lists together based on their position in the list. This can be useful when you want to perform operations on corresponding elements of two or more lists, such as adding or subtracting them.
- Iterating over multiple lists simultaneously - The zip() function can be used to iterate over multiple lists simultaneously, producing tuples containing the corresponding elements of each list. This can simplify the code and make it more readable, compared to using nested loops to iterate over each list.
- Merging dictionaries - You can use the zip() function to merge two dictionaries into a single dictionary, where the keys of each dictionary become the keys of the resulting dictionary, and the values of each dictionary become the values of the resulting dictionary.
- Transposing data - If you have a list of lists, you can use the zip() function to transpose the data, meaning that you can swap the rows and columns of the data. This can be useful when you want to perform operations on columns of data, instead of rows.
- Creating enumerated lists - You can use the zip() function with the range() function to create enumerated lists, where each item in the list is paired with a corresponding index number.
Conclusion:
The zip() function is a useful tool for manipulating and iterating over iterables in Python. Its versatility makes it a valuable tool in a variety of use cases.
- Python print statement "Syntax Error: invalid syntax"
- Installing Python Modules with pip
- How to get current date and time in Python?
- No module named 'pip'
- How to get the length of a string in Python
- ModuleNotFoundError: No module named 'sklearn'
- ModuleNotFoundError: No module named 'cv2'
- Python was not found; run without arguments
- Attempted relative import with no known parent package
- TypeError: only integer scalar arrays can be converted to a scalar index
- A value is trying to be set on a copy of a slice from a DataFrame
- ValueError: setting an array element with a sequence
- Indentationerror: unindent does not match any outer indentation level
- Valueerror: if using all scalar values, you must pass an index
- ImportError: libGL.so.1: cannot open shared object file: No such file or directory
- Python Try Except | Exception Handling
- Custom Exceptions in Python with Examples
- Python String replace() Method
- sqrt Python | Find the Square Root in Python
- Read JSON file using Python
- Binary search in Python
- Defaultdict in Python
- Int Object is Not Iterable – Python Error
- os.path.join in Python
- TypeError: int object is not subscriptable
- Python multiline comment
- Typeerror: str object is not callable
- Python reverse List
- strftime() in Python
- Typeerror: int object is not callable
- Python List pop() Method
- Fibonacci series in Python
- Python any() function
- Python any() Vs all()
- Python pass Statement
- Python Lowercase - String lower() Method
- Modulenotfounderror: no module named istutils.cmd
- Append to dictionary in Python : Key/Value Pair
- timeit | Measure execution time of small code
- Python Decimal to Binary
- GET and POST requests using Python
- Difference between List VS Set in Python
- How to Build Word Cloud in Python?
- Binary to Decimal in Python
- Modulenotfounderror: no module named 'apt_pkg'
- Convert List to Array Python