Python zip() function stores data inside it. This function accepts iterable elements as input and returns an iterable as the output.
If no iterable elements are provided to the python zip function, it returns an empty iterator.
It thus aggregates elements from the iterables and returns iterables of tuples.
Python Zip() Function Syntax:
zip(*iterators)
Python zip() function Parameters:
It can be containers/iterables (list,string,etc)
Value returned by the zip() function:
This function returns an iterable object mapping values from the corresponding containers.
Example: Basic understanding of Python zip() function
# initializing the input list
city = [ "Pune", "Ajanta", "Aundh", "Kochi" ]
code = [ 124875, 74528, 452657, 142563 ]
# zip() to map values
result = zip(city, code)
result = set(result)
print ("The zipped outcome is : ",end="")
print (result)
Output:
The zipped outcome is : {('Ajanta', 74528), ('Kochi', 142563), ('Aundh', 452657), ('Pune', 124875)}
Python zip() function with Multiple iterables
In case, if the user passes multiple iterables to the python zip() function, the function will return an iterable of tuples containing elements corresponding to the iterables.
Example:
numbers = [23,33,43]
input_list = ['five', 'six', 'seven']
# No iterables being passed to zip() function
outcome = zip()
result = list(outcome)
print(result)
# Two iterables being passed to zip() function
outcome1 = zip(numbers, input_list)
result1 = set(outcome1)
print(result1)
Output:
[]
{(23, 'five'), (33, 'six'), (43, 'seven')}
Python zip() function with an unequal length of iterable elements
numbers = [23, 33, 43]
input_list = ['one', 'two']
input_tuple = ('YES', 'NO', 'RIGHT', 'LEFT')
# the size of numbers and input_tuple is different
outcome = zip(numbers, input_tuple)
result = set(outcome)
print(result)
result1 = zip(numbers, input_list, input_tuple)
outcome1 = set(result1)
print(outcome1)
Output:
{(33, 'NO'), (43, 'RIGHT'), (23, 'YES')}
{(23, 'one', 'YES'), (33, 'two', 'NO')}
zip() function to unzip the values
The "*" operator
is used to unzip the values i.e. converting the elements back to the individual and independent values.
alphabets = ['a', 'c', 'e']
number = [1, 7, 9]
result = zip(alphabets, number)
outcome = list(result)
print(outcome)
test, train = zip(*outcome)
print('test =', test)
print('train =', train)
Output:
[('a', 1), ('c', 7), ('e', 9)]
test = ('a', 'c', 'e')
train = (1, 7, 9)
Conclusion
In this article, we have understood the working of Python’s zip() function.
References
- Python zip() function
- zip() function documentation