Reputation: 33
How can I make an integer from a list of integers? For example :from lst = [1, 2, 3] make a = 123? I tried that:
for i in lst:
print(i, end = '')
but if I need don't print, but just to have this number?
Upvotes: 3
Views: 96
Reputation: 254
You can use .join
method to create a string and convert it to int
like this:
a = int(''.join(str(x) for x in lst))
Cheers.
Upvotes: 1
Reputation: 164623
Using sum
with a generator expression:
lst = [1, 2, 3]
n = len(lst)
res = sum(val * 10**(n-idx) for idx, val in enumerate(lst, 1))
This is, in effect, a more explicit representation of what int('123')
should do internally.
Upvotes: 3
Reputation: 8277
You can use reduce
(functools.reduce
in Python3):
a = reduce( lambda x,y: 10*x + y, lst)
Upvotes: 3
Reputation: 82765
map
to convert element in list to stringstr.join
to concat the element in the listEx:
lst = [1, 2, 3]
print("".join(map(str, lst)))
If you need int
object
Use:
print(int("".join(map(str, lst))))
Upvotes: 4