eduardo,

welcome to programming, and even better, welcome to Python!  you've
done your research and found a list of great people who can help you
out.

with regards to your question, my comment are below...

> list1 = ['arr', 'bre', 'grau', 'lower', 'tudo']
> for item in list1:
>    if 'arr' in item:
>        print list1
> ###
> The output is (as expected):
> ['arr', 'bre', 'grau', 'lower', 'tudo']

you need to question your output here. sure it is what you *want*, but
i don't think you got it the way you originally thought.

what are you trying to do? are you trying to see whether the string
'arr' is in the entire list, or are you comparing one element at a
time and checking if a string is found in a larger string? (your code
is doing the latter.) here is some code (and output) which will
hopefully make it clear:

>>> list1 = ['arr', 'bre', 'grau', 'lower', 'tudo']
>>> 'arr' in list1
True
>>> 'bell' in list1
False
>>> 'grau' in list1
True

the "in" operator checks if an entire string is in a list or not. you
do not have to loop through it to get an answer. now let's iterate
through each string.

>>> for item in list1:
...     print item
...
arr
bre
grau
lower
tudo

notice that item represents each string in the list in each iteration
of the loop. if you are asking whether 'arr' is in item, you are
asking if 'arr' is in 'arr', 'arr' is in 'bre', 'arr' is in 'grau',
etc., so your (single) output is due to the fact that on the first
pass, 'arr' is in 'arr'. in other words, you did this:

>> tmp = 'arr'
>>> 'arr' in tmp
True
>>> 'arr' in 'arr'
True

so that's why your list printed out, because 'arr' in 'arr' returned
True. so, to really illustrate what you're doing, take a look at this
example:

>>> for item in list1:
...     if 'owe' in item:
...         print list1
...
['arr', 'bre', 'grau', 'lower', 'tudo']

this time, the output *is* expected, because 'owe' is *in* one of the
5 strings in your list... in particular, 'owe' is in 'lower', so
again, this is why list1 is printed, because that statement is True.


> Why this? I guess I'm not grasping the use of AND and OR

i don't think you have a problem with AND and OR... i think your
problem was with IN instead. :-) remember, for strings, IN means
whether a substring is found in a larger string (or not), and for
lists, IN means whether an object is found in the list (or not).

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
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to