Python Program to Convert a list of multiple integers into a single integer
There are times when we need to combine multiple integers from a list into a single integer in Python. This operation is useful where concatenating numeric values is required. In this article, we will explore efficient ways to achieve this in Python.
Using join()
join() method is the most efficient and clean method for combining integers into a single integer. It uses Python's built-in string manipulation functions and is simple to implement.
a = [1, 2, 3, 4]
# Convert integers to string, join, and convert back to integer
result = int("".join(map(str, a)))
print(result)
Output
1234
Explanation:
map(str, nums)converts each integer to a string."".join(...)combines these strings into one.int(...)converts the concatenated string back to an integer.
Let's explore some other methods on how to convert a list to multiple integers into a single integer.
Using Arithmetic
Arithmetic method uses arithmetic operations to construct the single integer directly. This method manually constructs the integer by shifting digits and adding new ones.
a = [1, 2, 3, 4]
# Build the integer using arithmetic
result = 0
for num in a:
result = result * 10 + num
print(result)
Output
1234
Explanation:
- Initialize
resultto0. - Multiply the current
resultby10to shift digits to the left. - Add the current number to
result.
Using List Comprehension and reduce()
This method uses functools.reduce() to achieve the result in a concise manner. This accumulates the result as a single integer.
from functools import reduce
a = [1, 2, 3, 4]
# Use reduce to build the integer
result = reduce(lambda x, y: x * 10 + y, a)
print(result)
Output
1234
Explanation:
reduce()applies the lambda function(x * 10 + y)cumulatively across all elements.
Using String Formatting
Another way to achieve this is by using string formatting to convert each integer into a string and join them.
a = [1, 2, 3, 4]
# String formatting and join
result = int(''.join(f"{i}" for i in a))
print(result)
Output
1234
Explanation:
- The string formatting
f"{i}"converts each integer to a string. ''.join(...)concatenates the strings which is then converted to an integer.