Newbie Q on searching lists

Wojtek Walczak gminick at hacker.pl
Sun Nov 24 04:33:15 EST 2002


Dnia Sat, 23 Nov 2002 05:45:55 GMT, Kenny Tilton napisał(a):
> I see the index method on lists throws an error if the element sought is 
> not found. I was hoping it would return None.
Yes, you're right, but it's easy to walk around:

def ind(list, arg):
    if arg in list:
       return list.index(arg)
    else:
       return 'None'

aList = [1, 'a', 2, 'b']

ind(a,'b') => 3
ind(a,7)   => 'None'

or even in one liner:

((c in a and (a.index(c),)) or ('None',))[0]

for example:

[((c in a and (a.index(c),)) or ('None',))[0] for c in ['b',6]]

returns: [3, 'None']

HTH.

-- 
[ ] gminick (at) underground.org.pl  http://gminick.linuxsecurity.pl/ [ ]
[ "Po prostu lubie poranna samotnosc, bo wtedy kawa smakuje najlepiej." ]



More information about the Python-list mailing list