1

Sorry, I'm very much a beginner to python. What I want to do is see which list an item is in. What I have is some lists set up like:

    l1 = [1,2,3]  
    l2 = [4,5,6]  
    l3 = [7,8,9]  

And let's say I want to find which list the item 5 is in. What I'm currently doing is:

    if l1.index(5)!=False:
        print 1
    elif l2.index(5)!=False:
        print 2
    elif l3.index(5)!=False:
        print 3

But this doesn't work. How would I do this?

Mrahta
  • 85
  • 6

3 Answers3

8

You can use in operator to check for membership:

>>> 5 in [1, 3, 4]
False
>>> 5 in [1, 3, 5]
True
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
1

In addition to the answer with the "in" operator, you should do that with a loop by inserting all the list to one list and then send it to a function and loop over it. Note that the first 'in' belongs to the for loop and the second 'in' is the operator:

l1 = [1,2,3]  
l2 = [4,5,6]  
l3 = [7,8,9]

all_lst = [l1,l2,l3]

list_contain_num(all_lst) 

def list_contain_num(all_lst):
    for lst in all_lst:
        if 5 in lst:
            print('the containing list is: ' + str(lst) )
Jongware
  • 22,200
  • 8
  • 54
  • 100
Nathan Barel
  • 348
  • 2
  • 14
0
if l1.index(5)!=False:
    print 1

The index() method does not return True or False, it returns the index. So you would change this to:

if l1.index(5) >= 0:
    print 1
dsh
  • 12,037
  • 3
  • 33
  • 51
  • What if it's not in the list? – Peter Wood Sep 25 '15 at 20:57
  • That's what the [docs](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) are for : ). Actually, it will raise a ValueError. Switching back from Java I was thinking it would return -1. At least the part about not comparing the returned value to a boolean literal is correct and helpful. – dsh Sep 25 '15 at 21:06