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:

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:

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:

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:

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