Open In App

Python Program to Convert a list of multiple integers into a single integer

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
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.

Python
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 result to 0.
  • Multiply the current result by 10 to 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.

Python
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.

Python
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.


Next Article

Similar Reads