python zip function
If you are a regular computer user, you should have used the .zip file extension. Do you know what it is? Basically, .zip is a container itself. It holds the real file inside. Similarly, Python zip is a container that holds real data inside. Python zip function takes iterable elements like input and returns an iterator. If Python zip function gets no iterable elements, it returns an empty iterator.
The syntax of zip() is:
zip(*iterables)
zip() Parameters
The zip() function takes:
iterables – can be built-in iterables (like: list, string, dict), or user-defined iterables (object that has __iter__
method).
Return Value from zip()
The zip() function returns an iterator of tuples based on the iterable object.
- If no parameters are passed, zip() returns an empty iterator
- If a single iterable is passed, zip() returns an iterator of 1-tuples. Meaning, the number of elements in each tuple is 1.
- If multiple iterables are passed, ith tuple contains ith Suppose, two iterables are passed; one iterable containing 3 and other containing 5 elements. Then, the returned iterator has 3 tuples. It’s because iterator stops when shortest iterable is exhaused.
Example
a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica") x = zip(a, b) #use the tuple() function to display a readable version of the result: print(tuple(x))
Output
(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))