[Tutor] Very basic question about lists

wesley chun wescpy at gmail.com
Tue Dec 23 00:36:11 CET 2008


> list1 = ['ar', 'fir', 'wo']
> list2 = ['ber', 'gar', 'gt']
> list3 = ['hu', 'mo', 'ko', 'tr']
> list4 = ['q', 'wer', 'duh']
>
> whole = [list1, list2, list3, list4]
> for item in whole:
>    if 'ar' or 'ko' in item:
>        print item
>
> So, the unexpected result was that I got all lists printed, when I
> expected only list1 and list3. Now, I don't know if I still understand
> the explanation given by spir -- I'll reread more carefully--, but I
> know that the code to get what I expect is this instead:
> for item in whole:
>    for word in item:
>        if word == 'ar' or word == 'ko':
>            print item
>
> I see I have to do a loop inside a loop and that this the right expression
> if word == 'ar' or word == 'ko':
>
> but this is not:
> if word == 'ar' or 'ko':


correct, but i *still* don't think you need to do an inner loop... it
seems you're just trying to see whether a word is in the list, not
checking for substrings. in fact, the lists can be inside another list
too. couple this with *not* looping through each list looking for
something, we have the following:

>>> whole = [
...     ['ar', 'fir', 'wo'],
...     ['ber', 'gar', 'gt'],
...     ['hu', 'mo', 'ko', 'tr'],
...     ['q', 'wer', 'duh'],
... ]
>>>
>>> for item in whole:
...     if 'ar' in item or 'ko' in item:
...         print item
...
['ar', 'fir', 'wo']
['hu', 'mo', 'ko', 'tr']

there... those are list1 and list3 right? again, the secret is in IN. :-)

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list