Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of multiple integers into a single integer?

How do I convert a list in Python 3.5 such as:

x=[1, 3, 5]

to an integer (int) of 135 ?

like image 487
homelessmathaddict Avatar asked Dec 09 '16 20:12

homelessmathaddict


People also ask

How do you convert a list of multiple integers into a single integer in Python?

Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.

How do I turn a list into an integer?

Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.

How do you convert a list of integers to a single string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

Here is a more mathematical way that does not have to convert back and forth to string. Note that it will only work if 0 <= i <= 9.

>>> x = [1, 3, 5]
>>> sum(d * 10**i for i, d in enumerate(x[::-1]))
135

The idea is to multiply each element in the list by its corresponding power of 10 and then to sum the result.

like image 105
brianpck Avatar answered Oct 10 '22 11:10

brianpck


If you have a list of ints and you want to join them together, you can use map with str to convert them to strings, join them on the empty string and then cast back to ints with int.

In code, this looks like this:

r = int("".join(map(str, x)))

and r now has the wanted value of 135.

This, of course, is a limited approach that comes with some conditions. It requires the list in question to contain nothing else but positive ints (as your sample) or strings representing ints, else the steps of conversion to string might fail or the joining of (negative) numbers will be clunky.

like image 44
Dimitris Fasarakis Hilliard Avatar answered Oct 10 '22 13:10

Dimitris Fasarakis Hilliard