Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert a list of multiple integers into a single integer in Python
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.
Using List Comprehension with join()
The join() method can join all items in a list into a string. We use list comprehension to convert each integer to a string, then join them together ?
Example
numbers = [22, 11, 34]
# Given list
print("Given list:", numbers)
# Convert each integer to string and join them
result = int("".join([str(i) for i in numbers]))
# Result
print("The integer is:", result)
The output of the above code is ?
Given list: [22, 11, 34] The integer is: 221134
Using map() with 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 string. Applying the int() function makes the final result an integer ?
Example
numbers = [22, 11, 34]
# Given list
print("Given list:", numbers)
# Use map to convert integers to strings, then join
result = int("".join(map(str, numbers)))
# Result
print("The integer is:", result)
The output of the above code is ?
Given list: [22, 11, 34] The integer is: 221134
Using String Formatting
Another approach is to use string formatting to concatenate the integers directly ?
Example
numbers = [22, 11, 34]
# Given list
print("Given list:", numbers)
# Use string formatting to concatenate
result = int(''.join(f'{num}' for num in numbers))
# Result
print("The integer is:", result)
The output of the above code is ?
Given list: [22, 11, 34] The integer is: 221134
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | Good | Fast | Explicit conversion |
| map() function | Very Good | Fastest | Functional programming |
| String Formatting | Excellent | Good | Modern Python style |
Conclusion
All three methods effectively convert a list of integers into a single integer by concatenation. The map() approach is generally the most efficient, while string formatting offers the cleanest syntax for modern Python code.
