zip()
?The zip() method in python returns a zip object by taking in iterables, like lists or strings, and aggregating them into tuples.
No parameter: When given no iterable as a parameter, zip()
returns an empty iterator.
Single parameter: When given a single iterable argument, zip()
returns an iterator of tuples with each tuple only having one element.
Multiple parameters: When given multiple iterables, zip()
returns an iterator of tuples with each tuple having multiple elements.
serialNumbers = [1, 2, 3]names = ['Sarah', 'John', 'Harry']# No iterables are passedresult = zip()print(result)# With a single iterableresult = zip(serialNumbers)print(result)# With multiple iterablesresult = zip(serialNumbers, names)print(result)
The purpose of this function is to map the elements of iterables to the same indexes in the tuples.
serialNumbers = [1, 2, 3]names = ['Sarah', 'John', 'Harry']result = zip(serialNumbers, names)print(result)# Now, to get a clear picture of how zip()# function is mapping both the iterables:for a,b in zip(serialNumbers, names):print(a,b)
In order to obtain the output in a readable format, you can use tuple()
to view the result in the form of tuples. You may also use list()
or set()
functions, as seen below:
serialNumbers = [1, 2, 3]names = ['Sarah', 'John', 'Harry']result = zip(serialNumbers, names)# Use tuple() function to read the resultprint(tuple(result))# Converting itertor to listresultList = list(result)print(resultList)# Converting to setresultSet = set(result)print(resultSet)
The iterator returned form zip()
stops when one of the input iterable is exhausted.
serialNumbers = [1, 2, 3, 4, 5] # length = 5names = ['Sarah', 'John', 'Harry'] # length = 3for a,b in zip(serialNumbers, names):print(a,b)
Free Resources