Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

best way to do some simple tasks

12 views
Skip to first unread message

Erik Lechak

unread,
Jan 29, 2003, 6:31:59 PM1/29/03
to
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

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

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

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

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.


Thanks,
Erik

Mark McEahern

unread,
Jan 29, 2003, 6:46:55 PM1/29/03
to
> 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]

lookup string formatting operations. Python doesn't have string
interpolation AFAIK, although there's been PEP(s?) for it.

> 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])?
>
> If I wanted to use reduce(), how do I shuffle the lists?

One way:

import operator
c = map(operator.add, 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.

ints are immutable, lists aren't.

a = range(1,5)
b = [x+1 for x in a]

Cheers,

// m

-


Jp Calderone

unread,
Jan 29, 2003, 6:46:31 PM1/29/03
to
On Wed, Jan 29, 2003 at 03:31:59PM -0800, 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

There have been many proposals regarding this. Suffice it to say none
have yet made it into the language.

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

or

a = map(str.strip, 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])?
>

import operator
c = map(operator.add, 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?

h -is- a reference to the element in the list. However, ints are
immutable. h += 1 above is the same as "h = h + 1", which rebinds h to a
new int object. If you want to change the elements of the list, iterate
over the indices of the list, like so:

d = range(5)
for h in range(len(d)):
d[h] = d[h] + 1

(soapbox) More generally, avoid using +=. It leads to just this sort of
confusion - Is it mutating the object in place, or rebind the variable to a
new object? It's often very difficult to tell. Stick to the long form for
immutable objects, and use methods for mutable ones (.append() for lists,
for example).

Jp

--
| This
| signature
| intentionally
| 8 lines
| long.
| (So sue me)
---
--
up 45 days, 3:49, 3 users, load average: 0.00, 0.07, 0.11

Brian Quinlan

unread,
Jan 29, 2003, 6:53:46 PM1/29/03
to
> 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


Paul Rubin

unread,
Jan 29, 2003, 7:01:44 PM1/29/03
to
ele...@bigfoot.com (Erik Lechak) writes:
> 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]

>

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

c = [a[i] + b[i] for i in range(len(a))]

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

Python doesn't have references.

holger krekel

unread,
Jan 29, 2003, 6:55:51 PM1/29/03
to
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

Erik Max Francis

unread,
Jan 29, 2003, 10:17:35 PM1/29/03
to
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 / m...@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.

Mike Meyer

unread,
Jan 29, 2003, 11:34:58 PM1/29/03
to
Jp Calderone <exa...@intarweb.us> writes:
> On Wed, Jan 29, 2003 at 03:31:59PM -0800, Erik Lechak wrote:
> > 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])?
> >
> import operator
> c = map(operator.add, a, b)

You can save the import with a bit of extra ugliness:

c = map(int.__add__, a, b)


<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

Alex Martelli

unread,
Jan 30, 2003, 5:20:35 AM1/30/03
to
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

I see you have received many helpful answers to your specific
questions so i'm not going to dwell on them. However, you may
also want to look into the book "Perl to Python Migration", by
Martin Brown, Addison-Wesley. I have not examined it in detail
myself, and the reviews are a bit mixed, but overall positive --
it might suit your needs quite well.


Alex

Michael Hudson

unread,
Jan 30, 2003, 7:20:03 AM1/30/03
to
Mike Meyer <m...@mired.org> writes:

> Jp Calderone <exa...@intarweb.us> writes:
> > On Wed, Jan 29, 2003 at 03:31:59PM -0800, Erik Lechak wrote:
> > > 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])?
> > >
> > import operator
> > c = map(operator.add, a, b)
>
> You can save the import with a bit of extra ugliness:
>
> c = map(int.__add__, a, b)

But then you lose polymorphism:

>>> int.__add__(1.0, 2.0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: descriptor '__add__' requires a 'int' object but received a 'float'

Cheers,
M.

--
But since I'm not trying to impress anybody in The Software Big
Top, I'd rather walk the wire using a big pole, a safety harness,
a net, and with the wire not more than 3 feet off the ground.
-- Grant Griffin, comp.lang.python

0 new messages