Python zip() Function with live practice example

Spread the love

In this tutorial, you will learn, how to use python zip() function.

This function takes iterables as input and combine them and return as iterator.

We need to convert iterator to a list or tuple. we can also use set function to convert iterator.

Syntax : zip(*iterators)
Parameters : iterables like lists, tuples, strings etc
Return Value : Returns a single iterator object

Program to Combine 2 lists:

In this below program we zip to lists and then we print list of values from iterator object by using list function.

ids = [ 1,2,3,4 ] marks = [ 40, 50, 60, 70 ] mapped = zip(ids,names) print(list(mapped))

Output:

[(1, 'ravi'), (2, 'raju'), (3, 'ramu'), (4, 'sid')]

Program to Combine 3 lists:

In this program, we uses 2 numerical lists and 1 string list to zip.

ids = [ 1,2,3,4 ] marks = [ 40, 50, 60, 70 ] names =['ravi','raju','ramu','sid'] # using zip() function mapped = zip(ids,names, marks) print(list(result))

Output:

[(3, 'ramu', 60), (4, 'sid', 70), (1, 'ravi', 40), (2, 'raju', 50)]

By using set function:

ids = [ 1,2,3,4 ] marks = [ 40, 50, 60, 70 ] names =['ravi','raju','ramu','sid'] # using zip() function mapped = zip(ids,names, marks) result=set(mapped) print(result)

Output:

{(3, 'ramu', 60), (4, 'sid', 70), (1, 'ravi', 40), (2, 'raju', 50)}

Unzipping :  Here we are going unzip the lists from zip 

# using zip() function mapped = zip(ids,names, marks) result=set(mapped) ids, marks, names = zip(*result) print("ids list", ids) print("marks list", marks) print("names list", names)

Output:

ids list (3, 4, 1, 2)
marks list (60, 70, 40, 50)
names list ('ramu', 'sid', 'ravi', 'raju')

There is a bug in this above program, If you found it, comment here. Lets try.

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *