Jorge Thame
Jorge Thame

Reputation: 131

Python concatenate list

I'm new to python and this is just to automate something on my PC. I want to concatenate all the items in a list. The problem is that

''.join(list)

won't work as it isn't a list of strings.

This site http://www.skymind.com/~ocrow/python_string/ says the most efficient way to do it is

''.join([`num` for num in xrange(loop_count)])

but that isn't valid python...

Can someone explain the correct syntax for including this sort of loop in a string.join()?

Upvotes: 13

Views: 39981

Answers (4)

jamylak
jamylak

Reputation: 133504

Here is another way (discussion is about Python 2.x):

''.join(map(str, my_list))

This solution will have the fastest performance and it looks nice and simple imo. Using a generator won't be more efficient. In fact this will be more efficient, as ''.join has to allocate the exact amount of memory for the string based on the length of the elements so it will need to consume the whole generator before creating the string anyway.

Note that `` has been removed in Python 3 and it's not good practice to use it anymore, be more explicit by using str() if you have to eg. str(num).

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1121296

You need to turn everything in the list into strings, using the str() constructor:

''.join(str(elem) for elem in lst)

Note that it's generally not a good idea to use list for a variable name, it'll shadow the built-in list constructor.

I've used a generator expression there to apply the str() constructor on each and every element in the list. An alternative method is to use the map() function:

''.join(map(str, lst))

The backticks in your example are another spelling of calling repr() on a value, which is subtly different from str(); you probably want the latter. Because it violates the Python principle of "There should be one-- and preferably only one --obvious way to do it.", the backticks syntax has been removed from Python 3.

Upvotes: 19

Aaron Digulla
Aaron Digulla

Reputation: 328556

If your Python is too old for "list comprehensions" (the odd [x for x in ...] syntax), use map():

 ''.join(map(str, list))

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

just use this, no need of [] and use str(num):

''.join(str(num) for num in xrange(loop_count))  

for list just replace xrange(loop_count) with the list name.

example:

   >>> ''.join(str(num) for num in xrange(10)) #use range() in python 3.x
    '0123456789'

Upvotes: 2

Related Questions