How do I convert a list in Python 3.5 such as:
x=[1, 3, 5]
to an integer (int) of 135
?
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.
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.
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.
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.
If you have a list of int
s 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 int
s 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 int
s (as your sample) or strings representing int
s, else the steps of conversion to string might fail or the joining of (negative) numbers will be clunky.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With