Combining items in a list - Python

Let's say I have a list in python, for example:

list=[1,2,3,4,5] 

How to combine the list so that it becomes:

 list= [12345] 

If anyone has a way to do this, we will be very grateful!

+4
source share
7 answers
 >>> list=[1,2,3,4,5] >>> k = [str(x) for x in list] >>> k ['1', '2', '3', '4', '5'] >>> "".join(k) '12345' >>> ["".join(k)] ['12345'] >>> >>> [int("".join(k))] [12345] >>> 
+7
source
 reduce(lambda x,y:10*x+y, [1,2,3,4,5]) # returns 12345 
+15
source

This is probably better:

 "%s" * len(L) % tuple(L) 

which can handle:

 >>> L=[1, 2, 3, '456', '7', 8] >>> "%s"*len(L) % tuple(L) '12345678' 
+9
source
 list=[int("".join(map(str,list)))] 
+3
source
 a = [1,2,3,4,5] result = [int("".join(str(x) for x in a))] 
+2
source

Is this really what you mean by list merging? You understand that a Python list may contain things other than numbers, right? You understand that Python is strongly typed and will not allow you to β€œadd” strings to numbers or vice versa, right? What should be the result of the "merging" of the list [1, 2, "hi mom"] ?

+1
source
 [int(reduce(lambda x,y: str(x) + str(y),range(1,6)))] 
0
source

All Articles