Combining List Items

I have a list like l=['a', 'b', 'c'] I want the line to be called "abc". Thus, in fact, the result is l[0]+l[1]+l[2] , which can also be written as

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

Is there any way to make this more elegant?

+6
source share
1 answer

Use str.join() :

 s = ''.join(l) 

The line in which you call this is used as the delimiter between the lines in l :

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

Using str.join() is much faster than combining elements one by one, because for each concatenation you need to create a new string object. str.join() only needs to create one new string object.

Note that str.join() will cycle through the input sequence twice. Once, to calculate how large the output line should be, and once again to build it. As a side effect, this means using a list expression 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]) 
+15
source

Source: https://habr.com/ru/post/944877/


All Articles