Vogelsire
Vogelsire

Reputation: 189

How to compare 2 list/array with python using for loops?

I want to compare ListA[0] to ListB[0]...etc.

ListA = [itemA, itemB, itemC]
ListB = [true, false, true]

for item in ListA:
    if ListB[item] == True:
        print"I have this item"

Current problem is that [item] is not a number, so ListB[item] will not work. What is the correct way if I want to do something like this?

Upvotes: 2

Views: 7341

Answers (7)

user1516849
user1516849

Reputation: 55

If you want to compare each element of ListA with the corresponding element of ListB (in other words the elements at the same index numbers), you can use a for loop that iterates over the index numbers rather than iterating over the actual elements of one list. So your code would be: (note that range(len(ListA)-1) gives you a list of the numbers from 0 to the length of ListA, minus 1 since it's 0-indexing)

for i in range(len(ListA)-1):
      //ListA[i] will give you the i'th element of ListA
      //ListB[i] will give you the i'th element of ListB

Upvotes: 1

Adem Öztaş
Adem Öztaş

Reputation: 21466

Or you can do something like this:

[ a for a,b in zip(ListA,ListB) if b==True ]

Upvotes: 1

Mirage
Mirage

Reputation: 31568

try this

for name,value in itertools.izip(ListA, ListB):
    if value == True:
        print "Its true"

Upvotes: 1

root
root

Reputation: 80396

You can use itertools.compress:

Docstring:
compress(data, selectors) --> iterator over selected data

Return data elements corresponding to true selector elements.
Forms a shorter iterator from selected data elements using the
selectors to choose the data elements.

In [1]: from itertools import compress

In [2]: l1 = ['a','b','c','d']

In [3]: l2 = [True, False, True,False]

In [4]: for i in compress(l1,l2):
   ...:     print 'I have item: {0}'.format(i)
   ...:     
I have item: a
I have item: c

Upvotes: 7

Ber
Ber

Reputation: 41873

Try this:

for item, have_it in zip(ListA, ListB):
    if have_it:
        print "I have item", item

Upvotes: 1

Tuim
Tuim

Reputation: 2511

You can use enumerate.

See this example:

http://codepad.org/sJ31ytWk

Upvotes: 1

Ifthikhan
Ifthikhan

Reputation: 1474

You can iterate through the lists this way.

for a, b in zip(ListA, ListB):
    pass

Upvotes: 7

Related Questions