for <var> in <sequence> if <condition>

Fredrik Lundh effbot at telia.com
Thu Oct 5 13:50:46 EDT 2000


Dave wrote:
> >What's wrong with
> >
> >    for line in lines:
> >        if line.strip().startswith('y'):
> >           doStuff(line)
> 
> Nothing at all. But then again, there's nothing wrong with 'x = x + 1'
> instead of 'x += 1', either. :)

if you're dealing with mutable objects, += might be something
completely different.

compare:

>>> a = []
>>> id(a)
7985436
>>> a += [1]
>>> a
[1]
>>> id(a)
7985436 <- same object

and

>>> a = []
>>> id(a)
7990508
>>> a = a + [1]
>>> a
[1]
>>> id(a)
7988636 <- new object

this might not make much sense for short lists, but it sure is a
good thing if you're using things like numpy and pil2...

</F>




More information about the Python-list mailing list