best way to do some simple tasks

Brian Quinlan brian at sweetapp.com
Wed Jan 29 18:53:46 EST 2003


>    What is the correct and best way to do this?
>    x =[1,2,3,4]
>    print "%(x[2])i blah" % vars() # <- does not work

print "%d blah" % (x[2])

> 2) Perform a method on each element of an array
>    a= ["  hello  ",  "  there  "]

Do you want to create a new list or not?

If you want to create a new one:

a = [s.strip() for s in a]

> 3) What is the best way to do this?
> 
>    a=[1,2,3]
>    b=[1,1,1]
> 
>    how do I get c=a+b (c=[2,3,4])?

c = [i+j for i,j in zip(a,b)]

> 4) Why does this work this way?
>    d=[1,2,3,4,5]
>    for h in d:
>       h+=1
>    print d
>    >>>[1, 2, 3, 4, 5]
> 
>    Is there a python reason why h is a copy not a reference to the
> element in the list?  In perl the h would be a ref.  If d was a tuple
> I could understand it  working this way.

No copy was created. I think that augmented assignment is a wart in
Python. For immutable types, augmented assignment causes a name
rebinding but for mutable types it causes the object to be modified.
Yuck.

Cheers,
Brian






More information about the Python-list mailing list