0
a = [1,2,3]
b = [4,5,6]
#i have 2 lists
for x in a:
 for y in b:
  print x,' vs ',y

Then i got

1 vs 4 , 1 vs 5, 1 vs 6 ,2 vs 4 ... and so on

I need only 3 results :- 1 vs 4 2 vs 5 3 vs 6

Mean 1st item on a with 1st item on b and 2nd with 2nd and 3rd with 3rd Please help me

Harry1992
  • 453
  • 1
  • 5
  • 12

6 Answers6

1

Try this:

a = [1,2,3]
b = [4,5,6]
[print('{0} vs {1}'.format(x,y)) for (x,y) in zip(a, b)]

Zip will join your two lists into ((1, 4), (2, 5), (3, 6))

Stuart Buckingham
  • 1,574
  • 16
  • 25
1

The other answers are fine, another approach would be using enumerate.

for i, x in enumerate(a):
    print x," vs ", b[i]

This generates a zipped list of sorts, where each value is paired with its index value in the list. E.g. enumerate([1, 2, 3]) => [(0, 1), (1, 2), (2, 3)].

Ben
  • 460
  • 5
  • 18
0
a = [1,2,3]
b = [4,5,6]

for first, second in zip(a,b):
    print(first, ' vs ', second)

zip ties together the values of a and b. So the first element of zip(a,b) is [1,4], the next element is [2,5] and so on. Note that zip creates an iterator, so you can't directly access the elements via index (zip(a,b)[1] doesn't work).

LcdDrm
  • 1,009
  • 7
  • 14
0

Try this brother:

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
print i + " / " + j

It will give you:

1 / 4
2 / 5
3 / 6

Also check: "for loop" with two variables?

0

Zip would be prefect for your use case.

More about zip: https://docs.python.org/2/library/functions.html#zip

a = [1,2,3]
b = [4,5,6]
for x in zip(a,b):
    print x[0],' vs ',x[1]

Note: If the size of your lists are different then zip stops at the smallest element

Vinjai
  • 13
  • 4
0

Thanks everyone zip(a,b) and enumerate(a,b) both working well but if i have lists like a = [1,2,3,4] and b = [1,2,3] then zip(a,b) only working 1,1 2,2 3,3 and the 4th var is not visible and the enumerate method is working well but in the end gives error out of range :)

Harry1992
  • 453
  • 1
  • 5
  • 12