# Python for loop with zip function

You use the zip when you wear pants and jackets. Have you noticed why we use this zip component?

You will say that ” we use the zip component in pants and jackets to keep our body completely covered from the outside environment “.

You must be right. But, from a technical point of view, we use Zip to convert more than one sequence component into a single sequence component.

Take a look at this diagram below so you can understand how more than one sequence is being turned into a sequence.

In Python, the zip function is like a real zip component that converts more than one sequence object( iterable object ) into a single sequence object( zip object ). So, look at this figure below

I think you may not have had a hard time understanding what I have discussed so far about the zip function!

You can use one or more sequence objects in different ways in a zip function. So, in terms of this usage, we will discuss the zip function divided into different categories.

• Zip function with no argument
• Zip function with one argument
• Zip function with n argument
• Passing arguments of unequal length

One thing to always keep in mind is that no matter how you pass the argument, the zip function will always return the iterator of tuple.

## Zip function with no argument

You can’t pass any arguments in the zip function. In this case, also the zip function will return you a tuple but there will be no element in it.

No_arguments = zip()
print(No_arguments)
print(list(No_arguments))

Output :

<zip object at 0x032168A8>
[]

So, the zip object here will always be in the form of Empty iterator. Which has since been converted to the Empty List.

## Zip function with one argument

When you pass only one iterable object in the zip function, it returns tuple’s iterator as the zip object.

One_argument = zip(range(5))
print(list(One_argument))

Output :

[(0,), (1,), (2,), (3,), (4,)]

Notice the output above, that one element will be present in each tuple of the sequence.

## Zip function with N argument

The N argument is called for here because you can pass more than one argument in a zip(a1, a2, ...,aN) function. So look at this concept below.

list1 = [a1, a2, a3, ......,aN]
list2 = [b1, b2, b3, ......,bN]
.
.
listN = [x1,x2,x3, .....,xN]
print(list(zip(list1,list2,...., listN)))

Output :

[(a1,b1, ...,x1), (a2,b2, ...,x2), .....,(aN,bN, ...,xN)]

Above it is not a program. The concept is represented in the form of a program to explain to you. N number of lists have been passed in the zip function and N number elements are stored in each list.

Here I will take two examples. In the first example, I will pass two arguments in the zip() function and in the second example I will pass three arguments.

### 1. Pass two arguments

Here I will use the range() function with the list in the zip() function.

Two_arguments = zip(range(len(List)),List)
print(list(Two_arguments))

Output :

### 2. Pass three arguments

Here we will create a nested tuple. That is, many internal tuples will be present in an external tuple. For example

company = ['google', 'fb', 'amazon', 'tesla']
salary = ['75k$', '65k$', '60k$', '55k$']
name = ['larry', 'mark', 'jef', 'elon' ]
Three_arguments = zip(name,company,salary)
print(tuple(Three_arguments))

Output :

(('larry', 'google', '75k$'), ('mark', 'fb', '65k$'), ('jef', 'amazon', '60k$'), ('elon', 'tesla', '55k$'))

Here are three arguments passed in the zip() function. As a result, the zip() function returns the tuple’s iterator that has been converted to a nested tuple.

## Passing arguments of unequal length

Suppose you are given two iterable objects. The length of one iterable object is n and the length of the other is q. And here n is greater than q.

In this case, if you pass both iterable objects in the zip() function, then the length of the zip object will be q.

So, always keep in mind when you pass more than one iterable object of unequal length into the zip function as an argument. Then the length of the zip object will be equal to the iterable object with that short length.

List = ['one', 'two', 'three', 'four']
Range = range(1,11)
print(list(zip(Range,List)))

Output :

[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

Notice in this program that the length of the list here is shorter than the range. So, the length of the tuple of iterator is equal to the length of the list.

In the case of unequal lengths, the zip() function always ignores the longest iterable object as an argument. If you want, you can make the length of the tuple of iterator equal to the length of the longest iterable object. For this, you need to take the help of itertools module.

Here you need to use the zip_longest() function that is present in the itertools module. If you want to replace the missing values with any other value, you can pass the fillvalue argument in the function.

from itertools import zip_longest
List1 = ['a1', 'a2', 'a3', 'a4']
List2 = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6']
print(list(zip_longest(List1,List2)))
print(list(zip_longest(List1,List2,fillvalue='0')))
print(list(zip_longest(List1,List2, fillvalue='$'))) Output : [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3'), ('a4', 'b4'), (None, 'b5'), (None, 'b6')] [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3'), ('a4', 'b4'), ('0', 'b5'), ('0', 'b6')] [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3'), ('a4', 'b4'), ('$', 'b5'), ('$', 'b6')] And if you don’t put any value in fillvalue, none will return as defaults. Even after this many people may have questions that how do I understand the zip object tuple of iterator! If an object is an iterator then you do not need to use the iter() function to access its elements, you can access every element of the iterator using the direct next() function. company = ['google', 'facebook', 'amazon', 'tesla'] name = ['larry', 'mark', 'jef', 'elon' ] Three_arguments = zip(name,company) print(next(Three_arguments)) print(next(Three_arguments)) print(next(Three_arguments)) print(next(Three_arguments)) Output : ('larry', 'google') ('mark', 'facebook') ('jef', 'amazon') ('elon', 'tesla') You notice this output above. Here the next() function returns to the tuple. So, then we can say that the zip object is the tuple of iterator. ## Convert Zip object to another Data type You can convert zip objects to different data types. In all the examples you have seen so far, the zip object has been converted to just a list. But, now you will see how to convert zip object to a tuple, list, set, and dictionary. List = ['One', 'Two', 'Three', 'Four'] zipped = zip(range(1,5),List) convert_list = list(zipped) print(convert_list) print(tuple(convert_list)) print(set(convert_list)) Output : [(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four')] ((1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four')) {(1, 'One'), (3, 'Three'), (2, 'Two'), (4, 'Four')} Notice here that when you convert a zip object to a tuple, it will become a nested tuple. You will notice that most of the time the zip() function is used to convert two iterable objects into a dictionary as keys and values. List = ['One', 'Two', 'Three', 'Four'] zipped = zip(range(1,5),List) zip_dict = dict(zipped) print(id(zip_dict)) print(zip_dict) Output : 23810408 {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'} If you want to update an element in the dictionary above, you need to use the update() method. And with the help of this method, you can also modify the elements of the dictionary. List1 =['five', 'six', 'seven'] zip_dict.update(zip(range(4,7),List1)) print(id(zip_dict)) print(zip_dict) Output : 20402536 {1: 'One', 2: 'Two', 3: 'Three', 4: 'five', 5: 'six', 6: 'seven'} You notice that the value of the 4 key has been modified to five. And the next elements have been updated. No new dictionaries have been created here because both have the same object id. ## Convert Zip object to Unzipping sequence You may think that there is a Python library function specified to convert a zip object to an unzip sequence. But no, no function is defined in the Python library for this. To perform this task, you need to use the unpacking operator * in the zip() function. So, you look at this program below. List = [(1,'a'), (2,'b'), (3,'c'), (4,'d')] seq1, seq2 = zip(*List) print(seq1) print(seq2) Output : (1, 2, 3, 4) ('a', 'b', 'c', 'd') And the second example is unzipped nested tuple. List = ((1,'a','#'), (2,'b','*'), (3,'c','#'),(1,'d','*')) seq1, seq2, seq3 = zip(*List) print(seq1) print(seq2) print(seq3) Output : (1, 2, 3, 1) ('a', 'b', 'c', 'd') ('#', '*', '#', '*') By looking at the above two examples you can understand that the sequence that you get as output as a result of unzipping is always in the form of tuple. ## Python for loop with Zip function Here you will see how Python for loop is being used with zip function. Here you can use the zip object with Direct Python for Loop. So, look at the syntax below. Second, you can separate the values ​​from the zip object or tuple of iterator like unzip. For this, you need to declare as many variables in the for loop as the number of iterable objects that make up a zip object. 1. How to display each element separately from the zip object on the screen with the help of for loop. List = ['a', 'b', 'c'] List1 = ['#', '$', '*']
for k,v in zip(List,List1):
print('latter :',k)
print('char:',v)

Output :

latter : a
char: #
latter : b
char: $latter : c char: * 2. How you can convert two lists into a separate dictionary. List = [1, 2, 3, 4] List1 = ['a', 'b', 'c', 'd'] Dict = {} for k,v in zip(List,List1): Dict[k]=v print(Dict) Output : {1: 'a', 2: 'b', 3: 'c', 4: 'd'} 3. Suppose you are given two lists, one containing integer numbers from 1 to 4 and the other lists characters from a to d. You write a program by which the elements of those two lists combine to return the right angle triangle as an output. List = [1, 2, 3, 4] List1 = ['a ', 'b ', 'c ', 'd '] for k,v in zip(List,List1): print(k*v) Output : a b b c c c d d d d 4. You are given a tuple of list here. And make two separate lists of maximum and minimum numbers from each tuple. Tuple_list = [(10,5,19),(90,67,80),(12,34,99),(95,100,92)] Min_tuple =[] Max_tuple =[] for var in Tuple_list: Min_tuple.append(min(var)) Max_tuple.append(max(var)) print('Min value of each tuple :',Min_tuple) print('Max value of each tuple :',Max_tuple) Output : Min value of each tuple : [5, 67, 12, 92] Max value of each tuple : [19, 90, 99, 100] 5. How to create a new dictionary as a result of dictionary comprehension. Company = ['Google', 'microsoft', 'fb', 'spacex'] Founder = ['Larry', 'Bill', 'Mark', 'Elon'] Company_founder = {k:v for k,v in zip(Company,Founder)} print(Company_founder) Output : {'Google': 'Larry', 'microsoft': 'Bill', 'fb': 'Mark', 'spacex': 'Elon'} 6. How to convert key-value pair of a dictionary to value-key pair my_dict = {1: 'a', 2: 'b', 3: 'c'} swapped_dict = dict(zip(my_dict.values(), my_dict)) print(swapped_dict) swapped_dict = dict(zip(my_dict.values(), my_dict.keys())) print(swapped_dict) swapped_dict = {k:v for v,k in my_dict.items()} print(swapped_dict) Output : {'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3} ## Frequently Asked Questions (FAQ’s) 1. What is the main difference between a zip function and a zip object? And how a zip function converts one or more iterable objects into zip objects. The zip() function is the Python library function. That is already stored in the Python library. And zip function to convert one or more iterable objects to zip objects. And zip object is a kind of object which is stored in the frame of the tuple of iterator. To get the zip object you have to pass the iterable objects through the zip function. And this zip function will convert one or more iterable objects into a single object. Which works a lot like a real-life zip component. 2. Is the zip object iterable or iterator? Here the zip object is the iterator object. So, you will be able to directly access each element using the next() function with the zip object. 3. How do you sort the elements of a zip object using a short function? When you pass a zip object through a sorted() function, this function will sort the first elements of the zip object in order. List1 = ['c', 'a', 'd', 'b'] List2 = [3, 4, 2, 1] print(sorted(zip(List1,List2))) print(sorted(zip(List2,List1))) Output : [('a', 4), ('b', 1), ('c', 3), ('d', 2)] [(1, 'b'), (2, 'd'), (3, 'c'), (4, 'a')] 4. Suppose, if two iterable objects of unequal length are passed through the zip function, what will be the length of the zip object? In this case, the length of the zip object will be equal to the iterable object with that short length. So, take a look at this program below. List1 = ['a', 'b', 'c','d'] List2 = ['#', '$', '*']
print('len of zip object :',len(List2))

Output :

len of zip object : 3

6. How do you create a new dictionary using Python for loop with zip function?

Here you need to convert the zip object to a dictionary with the help of dict() function. To get this answer, look at problem number five above.

## Conclusion

When someone starts learning Python, the concept of Python for Loop may seem very difficult. Because the concept of Python for Loop is completely different from all other programming languages.

To learn Python for loop well, first of all, you have to have a good idea about iterator and iterable object. So, you have to understand which is the iterable object and which is not.

This tutorial discusses Python for loop with zip function. And here all the concepts of zip function before Python for loop are discussed. Also, every concept of Python for Loop with Zip function is presented to you in a simple way with examples.

If this tutorial has added any value in your education life then don’t forget to share this tutorial with your friends. And if I have made a mistake in this tutorial, please comment and I will correct my mistake. Thanks