Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate elements of a list [duplicate]

I have a list like l=['a', 'b', 'c'] I want a String like 'abc'. So in fact the result is l[0]+l[1]+l[2], which can also be writte as

s = ''
for i in l:
    s += i

Is there any way to do this more elegantly?

like image 557
Tengis Avatar asked May 13 '13 12:05

Tengis


People also ask

How do you merge duplicates in python list?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

How do I combine two lists of elements?

Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you concatenate two lists without duplicates in Python?

Use set() and list() to combine two lists while removing duplicates in the new list and keeping duplicates in original list. Call set(list_1) and set(list_2) to generate sets of the elements in list_1 and list_2 respectively which contain no duplicates.

Does list concatenation create a new list?

Yes: list1 + list2 . This gives a new list that is the concatenation of list1 and list2 .


1 Answers

Use str.join():

s = ''.join(l)

The string on which you call this is used as the delimiter between the strings in l:

>>> l=['a', 'b', 'c']
>>> ''.join(l)
'abc'
>>> '-'.join(l)
'a-b-c'
>>> ' - spam ham and eggs - '.join(l)
'a - spam ham and eggs - b - spam ham and eggs - c'

Using str.join() is much faster than concatenating your elements one by one, as that has to create a new string object for every concatenation. str.join() only has to create one new string object.

Note that str.join() will loop over the input sequence twice. Once to calculate how big the output string needs to be, and once again to build it. As a side-effect, that means that using a list comprehension instead of a generator expression is faster:

slower_gen_expr = ' - '.join('{}: {}'.format(key, value) for key, value in some_dict)
faster_list_comp = ' - '.join(['{}: {}'.format(key, value) for key, value in some_dict])
like image 73
Martijn Pieters Avatar answered Oct 08 '22 21:10

Martijn Pieters