best way to do some simple tasks

holger krekel pyth at devel.trillke.net
Thu Jan 30 00:55:51 CET 2003


Erik Lechak wrote:
> Hello all,
> 
> I am transitioning from perl to python.  I find myself trying to do
> many things in a perlish way.  Perl made many common tasks such as
> string manipulations easy (in a perlish sort of way).  So I was
> wondering if someone could suggest the "pythonish" way of doing these
> things.  I have read tons of documentation and can do all of the
> following tasks, but my code does not look "professional".
> 
> 
> 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

     print "%d blah" % x[2]

if you want to work with named references:

    x2 = x[2]
    print "%(x2)d blah" % locals()

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

    map(str.strip, a)

You can use this pattern whenever a method doesn't need additional
arguments (except the first 'self' instance parameter).
    
> 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])?

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

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

I don't see an obvious way to use reduce here. sorry.

> 4) Why does this work this way?
>    d=[1,2,3,4,5]
>    for h in d:
>       h+=1

because the 'for loop' rebinds the local name 'h' every
time it iterates to the next value.  Any rebinding 'h+=1'
in the loop-body is meaningless for the next iteration step. 
It's especially misleading if you think of 'h' as a
direct reference to memory.

>    Is there a python reason why h is a copy not a reference to the
> element in the list?

'h' is a name and it is bound either locally or globally
to some object.  Assignment modifies the namespace binding
but not the object itself.  Moreover, Integers, Strings and tuples
are immutable objects and thus can't be modified, ever.

HTH,

    holger





More information about the Python-list mailing list