Single Line Nested For Loops Python

 

It is possible to iterate two for loops in one single line in python. For doing this, you can use the built in  zip function. You can see the example how to use zip function in the python. 

Code:

list1 = ['Abbas', 'Ali', 'Usman']
list2 = ['Kamran', 'Asgar', 'Hamza', 'Umer']
list3 = []
for i,j in zip(list1,list2):
    list3.append(i)
    list3.append(j)
print(list3)

Output:

['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']

So, by using zip function, we can use two for loops or we can iterate two lists in same row.

avatar
AUTHOR: Muhammad Abbas
I am Software Engineer.

0 Comments