best way to do some simple tasks

Erik Max Francis max at alcyone.com
Thu Jan 30 04:17:35 CET 2003


Erik Lechak wrote:

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

There are many templating systems that can do this sort of thing for
you, but there's no direct (builtin) way to do this in Python.  In
short, that's not what the format specifiers are for.

> 2) Perform a method on each element of an array
>    a= ["  hello  ",  "  there  "]
> 
>    how do I use the string's strip() method on each element of the
> list?
> 
>    a = map((lambda s: s.strip()), a) # looks ugly to me
> 
>    for e in a:                       # this looks even worse
>       temp.append(e.strip())
>    a=temp

	a = [x.strip() for x 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])?

	[x + y for x, y in zip(a, b)]

>    If I wanted to use reduce(), how do I shuffle the lists?

I'm not sure what you're asking here.

> 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.

Python is not Perl.  This doesn't work because integers (as well as some
other fundamental objects) are immutable, so you're getting a reference
to the object but you can't do anything with it.  When you write h += 1,
what you're really doing is rebinding the (local) variable h with a
brand new object:

>>> h = 1
>>> id(h)
135297120
>>> h += 1
>>> id(h)
135297096

For immutable objects, x += y is the same as x = x + y, and the x + y
creates a new object.  To translate that code to Python, you'd probably
want to use a list comprehension:

	d = [x + 1 for x in d]

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The work will teach you how to do it.
\__/ (an Estonian proverb)
    Python chess module / http://www.alcyone.com/pyos/chess/
 A chess game adjudicator in Python.




More information about the Python-list mailing list