1.

What is the use of built-in zip() function. Explain with suitable examples.

Answer»

Python’s object hierarchy has a built-in zip object. It is an iterator of tuples containing items on the same index stored in ONE or more iterables. The zip object is returned by zip() FUNCTION. With no arguments, it returns an empty iterator.

>>> a=zip() >>> type(a) <class 'zip'> >>> list(a) []

When one iterable is provided, zip() function returns an iterator of one element tuples.

>>> a=zip('abcd') >>> list(a) [('a',), ('b',), ('c',), ('d',)]

When the function has MULTIPLE iterables as arguments, each tuple in zip object contains items at similar index. Following SNIPPET gives two lists to zip() function and the result is an iterator of two element tuples.

>>> l1=['pen', 'computer', 'book'] >>> l2=[100,20000,500] >>> a=zip(l1,l2) >>> list(a) [('pen', 100), ('computer', 20000), ('book', 500)]

Iterable arguments may be of different length. In that case the zip iterator stops when the shortest input iterable is exhausted.

>>> string="HelloWorld" >>> lst=list(range(6)) >>> tup=(10,20,30,40,50) >>> a=zip(string, lst, tup) >>> list(a) [('H', 0, 10), ('e', 1, 20), ('l', 2, 30), ('l', 3, 40), ('o', 4, 50)]

The zip object can be unpacked in separate iterables by prefixing * to zipped object.

>>> a=['x', 'y', 'z'] >>> b=[10,20,30] >>> c=zip(a,b) >>> result=list(c) >>> result [('x', 10), ('y', 20), ('z', 30)] >>> x,y=zip(*result) >>> x ('x', 'y', 'z') >>> y (10, 20, 30)


Discussion

No Comment Found