[Tutor] Noob question

wesley chun wescpy at gmail.com
Tue Dec 11 23:05:56 CET 2007

> > > This is fairly inefficient.  Because strings in python are immutable
> > > this approach causes a new string to be created every iteration.
> >
> >This is not true of CPython (the standard python.org release) since
> >version 2.4:
> >http://www.python.org/doc/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000

i'm also fairly certain that this minor improvement only works for
strings and not other sequences.  it is also not recommended to
concatenate lists either, for similar reasons.  it's better to use the
list.extend() method to add the contents of one list to another,
rather than creating a 3rd list which is the sum of the 1st pair.

to its defense however, i have seen some use cases where list
concatenation is the simplest choice in the code. it usually occurs
when you need a list but with a couple more items added to it (so you
can act upon the larger list), and neither append() nor extend() have
return values. now whether or not you wish to modify the original list
needs to be figured in as well.

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list