Convert a list of multiple integers into a single integer in Python

PythonServer Side ProgrammingProgramming

Sometimes we may have a list whose elements are integers. There may be a need to combine all these elements and create a single integer out of it. In this article we will explore the ways to do that.

With join

The join method can Join all items in a tuple into a string. So we will use it to join each element of the list by iterating through them through a for loop.

Example

 Live Demo

listA = [22,11,34]
# Given list
print("Given list A: ", listA)
# Use
res = int("".join([str(i) for i in listA]))
# Result
print("The integer is : ",res)

Output

Running the above code gives us the following result −

Given list A: [22, 11, 34]
The integer is : 221134

With map and join

We can apply the map function to convert each element of the list into a string and then join each of them to form a final list. Applying the int function makes the final result an integer.

Example

 Live Demo

listA = [22,11,34]
# Given list
print("Given list A: ", listA)
# Use
res = int("".join(map(str, listA)))
# Result
print("The integer is : ",res)

Output

Running the above code gives us the following result −

Given list A: [22, 11, 34]
The integer is : 221134
raja
Published on 20-May-2020 14:07:29
Advertisements