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?
Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.
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.
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.
Yes: list1 + list2 . This gives a new list that is the concatenation of list1 and list2 .
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With