Home > OS >  What is the right function to use for for loop with 2 arguments?
What is the right function to use for for loop with 2 arguments?

Time:12-15

I'm currently stuck and have no idea what function or code of line I should type. Hopefully, I can get some idea here. Whenever I try to print it keeps giving me an error.

for i1,i2 in range(len(mc_name, mc_class)):
i1 = i1   1
i2 = i2   1
print(mc_name[i1]   mc_class[i2])

Error:
for i1,i2 in range(len(mc_name, mc_class)): 
TypeError: len() takes exactly one argument (2 given)

CodePudding user response:

Looks like you might want zip.

for i1, i2 in zip(mc_name, mc_class):
    print(i1   i2)

zip takes any number of iterables as arguments, and produces a single iterable that takes elements from each one -- hence it lets you iterate over two (or any number!) lists together in parallel. If the input iterables are of unequal length, it stops as soon as any one of them is exhausted.

The equivalent using len would be to take the minimum length of the two lists as the argument to range:

for i in range(min(len(mc_name), len(mc_class))):
    print(mc_name[i]   mc_class[i])

but zip is preferred because it's more concise.

If you don't want to iterate over the two lists in parallel, and instead want the product of the two lists (i.e. every item with every other item) that would be a nested loop:

for i1 in mc_name:
    for i2 in mc_class:
        print(i1   i2)

or itertools.product:

from itertools import product
for i1, i2 in product(mc_name, mc_class):
    print(i1   i2)

CodePudding user response:

I think you mean

for i1,i2 in zip(mc_name, mc_class):

CodePudding user response:

I think you are probably looking for the zip() function.

Assuming that, mc_name and mc_class have same length you can write as follows:

for (i1, i2) in zip(mc_name, mc_class):
    print(i1   i2)

or, if you want to use len then write as follows

for i in range(len(mc_name)): # You can also use len(mc_class)
    print(mc_name[i]   mc_class[i])

Note : If you are using a for loop with range or in e.g.

for i in range(x):

or

for i in some_list:

You don't need to put this line i =1 or i=i 1

  • Related