0

I am wondering if there is a nice way to convert a list of digits to an integer in python. That is, if I have mylist = [1, 5, 9] I would like to do something like int(mylist) to get an output of 159. I am assuming that the input list simply has digits, and I want to use this to create a number. Currently the best I have is:

mylist = [1, 5, 9]
num = 0
for i in range(len(mylist)):
    num += mylist[i] * 10 ** (len(mylist) - i - 1)

Which should work alright, but feels too explicit. Is there a neater/nicer way to do this?

Math chiller
  • 4,078
  • 6
  • 25
  • 42

5 Answers5

1

You might want to reconsider how your data got into that structure and fix that.

But you can easily combine it as a string and call int() on it:

int("".join(str(i) for i in mylist))
monkut
  • 39,454
  • 22
  • 115
  • 146
0

Currently the best I can think of is:

mylist = [1, 5, 9]
num = 0
for i in range(len(mylist)):
    num += mylist[i] * 10 ** (len(mylist) - i - 1)
Math chiller
  • 4,078
  • 6
  • 25
  • 42
0

Try this:

list = [1, 2, 3]
string = ''
for num in list:
    string = string + str(num)
result = int(string)
print(result)
CircuitSacul
  • 1,201
  • 6
  • 25
0

The map function is generally faster. I used a lambda, but you could also just create your own function instead of a lambda.

mylist = [1, 5, 9]
N = len(mylist)
sum(list(map(lambda x : x[0]*10**(N-x[1]-1),  enumerate(mylist))))
targetXING
  • 81
  • 9
0

Use functools.reduce:

from functools import reduce

assert reduce(lambda a, x: 10*a + x, [1,5,9]) == 159

This is a short way of implementing Horner's Method.

chepner
  • 446,329
  • 63
  • 468
  • 610