zip() function is used to group multiple iterators. Look at the doc of the zip() function using help method. Run the following code to get the help on zip() function.
Example
help(zip)
If you run the above program, you will get the following results.
Output
Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.
Let's see a simple example of how it works?
Example
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zipping both ## zip() will return pairs of tuples with corresponding elements from both lists print(list(zip(names, ages)))
If you run the above program, you will get the following results
Output
[('Harry', 19), ('Emma', 20), ('John', 18)]
We can also unzip the elements from the zipped object. We have to pass the object with a preceding * to the zip() function. Let's see.
Example
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zipping both ## zip() will return pairs of tuples with corresponding elements from both lists zipped = list(zip(names, ages)) ## unzipping new_names, new_ages = zip(*zipped) ## checking new names and ages print(new_names) print(new_ages)
If you run the above program, you will get the following results.
('Harry', 'Emma', 'John') (19, 20, 18)
General Usage Of zip()
We can use it to print the multiple corresponding elements from different iterators at once. Let's look at the following example.
Example
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## printing names and ages correspondingly using zip() for name, age in zip(names, ages): print(f"{name}'s age is {age}")
If you run the above program, you will get the following results.
Output
Harry's age is 19 Emma's age is 20 John's age is 18