In this tutorial, we’ll explore different ways to convert a list of integers into a single integer i.e., converting a list of multiple integers such as [1,2,3,4,5] into a single integer that is 12345. There are multiple approaches by which we can do this. Let’s discuss some of them.
- Method 1: Using String Concatenation.
- Method 2: Using Join Function.
- Method 3: Using Map with Join Function.
If you want to learn more about Python, Visit Python Tutorials.
using string concatenation to Convert a list of multiple integers into a single integer
If you want to concatenate a list of numbers into a single string, iterate over the list using a loop and add all the elements into a variable using string concatenation. The str() function allows you to convert any variable of any data type to a string. The code below shows how to apply the str() function and for the loop to convert a list of integers into a single integer.
#Using String Concatenation
List1 = [1, 2, 3, 4, 5] # declaring a list
# create a variable to store final integer
var = ''
#iterate over the list elements
for element in List1:
# converting integer to string and adding into variable
var += str(element)
# converting back into integer and printing the final result
print(int(var))
Output:
12345
using join function to turn a list of multiple integers in single integer
Another method is to use a join() function but it can be used only with strings. Therefore, before applying this function, we need to convert integers into strings. Then apply the join() function to concatenate them into a single variable.
#Using Join Function to convert a list of multiple integers into a single integer
# declare a list
List1 = [9, 5, 3, 6, 7, 2, 4]
# converting integers to strings
List1 = [str(element) for element in List1]
# joining all the elements and converting it back into integer
new_integer = int(''.join(List1))
# printing the result
print(new_integer)
Output:
9536724
Using map() with join function
In the previous method, we need to convert a list of integers into a string in order to apply the join function. For this, we need to iterate over the list to convert each integer to a string. Instead of iterating over the whole list, we can use a map() function. The map function takes two arguments as input: the input list and the desired data type as shown in the example below.
In this example, we want to convert a list1 of integers into a string. It takes two inputs and converts the list1 into the desired datatype.
# Using Map with Join Function to convert a list of multiple integers into a single integer
# create a list
List1 = [7, 9, 1, 4, 5]
# converting the items of list1 into string using map function, join them and then convert the final result to integer datatype
new_integer = int(''.join(map(str, List1)))
# print the final result
print("Result: ", new_integer)
Output:
Result: 79145