Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 898
Jorge Thame Avatar asked Aug 15 '12 10:08

Jorge Thame


People also ask

How do you concatenate a list in Python?

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

How do I concatenate two strings in a list in Python?

Using + operator This is an easy way to combine the two strings. The + operator adds the multiple strings together. Strings must be assigned to the different variables because strings are immutable. Let's understand the following example.

Can you append two lists in Python?

There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.


2 Answers

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.

like image 66
Martijn Pieters Avatar answered Oct 13 '22 21:10

Martijn Pieters


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

like image 6
jamylak Avatar answered Oct 13 '22 22:10

jamylak