0

This is probably a very easy thing to solve in Python, but I would appreciate anyone's help. I have two lists where I want to loop through but only for matched items:

lista = ['a', 'b', 'c']
listb = ['a1', 'b1', 'c1']


for a in lista:
    for b in listb:
        print 'my first item is:', a, 'and my second item is:', b

This will print

my first item is: a and my second item is: a1
my first item is: a and my second item is: b1
my first item is: a and my second item is: c1
my first item is: b and my second item is: a1
my first item is: b and my second item is: b1
my first item is: b and my second item is: c1
my first item is: c and my second item is: a1
my first item is: c and my second item is: b1
my first item is: c and my second item is: c1

How can I make it print only:

my first item is: a and my second item is: a1
my first item is: b and my second item is: b1
my first item is: c and my second item is: c1
RJL
  • 341
  • 1
  • 7
  • 19

4 Answers4

0

This solution assumes both lists are of equivalent size.

for i in range(0, len(lista)):
    print lista[i], listb[i]
James
  • 274
  • 4
  • 12
  • I should add there are more "Pythonic solutions" to your question but this will help with your understanding. – James Jun 28 '18 at 06:22
0

You're looking for zip. It will return an iterator of tuples of each pair of elements.

>>> for z in zip(lista, listb):
...   print('my items are: {}, {}'.format(*z))
...
my items are: a, a1
my items are: b, b1
my items are: c, c1
dimo414
  • 47,227
  • 18
  • 148
  • 244
0

Try using zip. What zip does is it maps items in your lists. For for e.g. items at index 0 after zip will be (a,a1) and so on.

lista = ['a', 'b', 'c']
listb = ['a1', 'b1', 'c1']
for a in zip(lista,listb):
    print ('my items are:', a)
Raghav Patnecha
  • 716
  • 8
  • 29
0

you can use zip to loop over two list simultaneously

lista = ['a', 'b', 'c']
listb = ['a1', 'b1', 'c1']


for a,b in zip(lista,listb):
    print 'my items are:', a, b

output :

my items are: a a1
my items are: b b1
my items are: c c1

according to index matching will be done!

Onk_r
  • 836
  • 4
  • 21