Kyra Elizabeth
Kyra Elizabeth

Reputation: 51

Merging items in a list - Python

Say I have a list in python, like such:

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

How would I merge the list so that it becomes:

list= [12345]

If anyone has a way to do this, it would be greatly appreciated!!

Upvotes: 4

Views: 5729

Answers (7)

Karl Knechtel
Karl Knechtel

Reputation: 61643

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

Upvotes: 1

Kabie
Kabie

Reputation: 10663

This probably better:

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

which can handle:

>>> L=[1, 2, 3, '456', '7', 8]
>>> "%s"*len(L) % tuple(L)
'12345678'

Upvotes: 9

kzh
kzh

Reputation: 20638

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

Upvotes: 0

Utku Zihnioglu
Utku Zihnioglu

Reputation: 4883

list=[int("".join(map(str,list)))]

Upvotes: 3

Steve Tjoa
Steve Tjoa

Reputation: 61124

reduce(lambda x,y:10*x+y, [1,2,3,4,5])
# returns 12345

Upvotes: 15

pyfunc
pyfunc

Reputation: 66739

>>> 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]
>>> 

Upvotes: 8

carl
carl

Reputation: 50564

a = [1,2,3,4,5]
result = [int("".join(str(x) for x in a))]

Upvotes: 2

Related Questions