On 4/26/2010 3:38 PM, C M Caine wrote:
Why does this not work:
By "work" you mean "do what I want it to do".
>>> L = [' foo ','bar ']
>>> for i in L:
i = i.strip()
This creates a new local variable named i. It does not affect L. This
has nothing to do with loops nor is it strange behavior - it is expected
behavior.
Consider the loopless equivalent:
>>> i = L[0]
>>> i = i.strip()
>>> L
[' foo ', 'bar ']
>>> L
[' foo ', 'bar ']
>>> # note the leading whitespace that has not been removed.
But this does:
>>> L = [i.strip() for i in L]
>>> L
['foo', 'bar']
What other strange behaviour should I expect from for loops?
None - loops do not have "strange" behaviors.
Perhaps "unexpected" but that is a result of not understanding an aspect
of the language.
--
Bob Gailer
919-636-4239
Chapel Hill NC
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor