[Tutor] Pythonic way of concatenation of elements in an array
Steven D'Aprano
steve at pearwood.info
Fri Jan 27 00:04:18 CET 2012
spawgi at gmail.com wrote:
> Hello,
>
> My code is -
>
> l = len(m)
> item = str(m[1])
> for i in range(2,l):
> item = item + "-" + str(m[i])
>
> This code is part of a bigger function. It works fine. But I am not happy
> with the way I have written it. I think there is a better (Pythonic) way to
> rewrite it.
> If anyone knows how to improve this snippet, I would be very thankful.
(1) Never use "l" as a variable name, as it looks too much like 1.
(2) Use meaningful names. When posting snippets for help, you should show
example data.
(3) You almost never need to iterate over an index by hand. Instead iterate
over the items themselves. That is, instead of this:
for i in len(sequence):
do_something_with( sequence[i] )
do this instead:
for item in sequence:
do_something_with( item )
and similar variations.
(4) When you want only part of a sequence, use slicing to extract just the
parts you care about.
(5) When assembling strings from substrings, never use repeated concatenation
using + as that can be EXTREMELY slow. Use str.join to build the string in one
assignment, instead of multiple assignments.
Your code shown above is *very* inefficient and will be PAINFULLY slow if m is
very large. To understand why, you should read this article:
http://www.joelonsoftware.com/articles/fog0000000319.html
In this case, you can replace your snippet with this:
result = '-'.join(str(item) for item in m[1:])
For example:
py> m = [1, 2, "hello world", (23, 42), 5]
py> '-'.join(str(item) for item in m[1:])
'2-hello world-(23, 42)-5'
--
Steven
More information about the Tutor
mailing list