/    /  Python – ZIP

Python ZIP

Zip is a function which is an iterator of the tuples which pairs the consecutive items or elements in the given tuples. This function returns zip. The size of the zip is determined by the tuple with the least number of elements.

Syntax:

zip(*iterators)


where iterators can be built in iterators like string, list etc., or user defined iterators.

  • If no parameters are passed in the zip, then zip() returns an empty iterator.
  • If only one parameter is passed in the zip, then zip() returns an iterator of tuple where each tuple contains only one element or item.
  • If multiple parameters or iterators are passed in the zip, then zip() returns an iterator of tuple where each tuple consists of elements provided.


Python Code:

name=("Peter","Chandler","Ali","Suraj")
place=("Mexico","Manhattan","karachi","Delhi")
age=(25,32,35,37)
x=zip(name,place,age)
list(x)


Output:


[(‘Peter’, ‘Mexico’, 25),

 (‘Chandler’, ‘Manhattan’, 32),

 (‘Ali’, ‘karachi’, 35),

 (‘Suraj’, ‘Delhi’, 37)]

If we pass different number of iterators in the zip, then size of the zip is determined by the tuple with least number of elements.


Python Code:

name=("Vijay","Rani","George","Suzy")
items=("Chocolates","Biscuits","cake","chips","sandwich")
quantity=(50,10,2)
y=zip(name,items,quantity)
list(y)


Output:

[(‘Vijay’, ‘Chocolates’, 50), (‘Rani’, ‘Biscuits’, 10), (‘George’, ‘cake’, 2)]