How to Convert List to Integer in Python
To convert a list to an integer in Python, you can use the map() function or list comprehension.
The following examples show how to convert a list to an integer in Python using these two methods.
Using map() Function
We can use the map() function to convert a list of strings to a list of integers.
Suppose we have the following list:
# Create a list of numbers as strings
num_str = ["25", "27", "45", "36", "41", "30"]
# Convert list to integer
num_int = list(map(int, num_str))
# Show integer
print(num_int)
Output: 👇️
[25, 27, 45, 36, 41, 30]
In this example, we use the map() function to convert the list of strings num_str to a list of integers num_int. The output shows the list of integers converted from the list of strings using the map() function.
Using List Comprehension
We can use list comprehension to convert a list of strings to a list of integers.
Suppose we have the following list:
# Create a list of numbers as strings
num_str = ["25", "27", "45", "36", "41", "30"]
# Convert list to integer
num_int = [int(x) for x in num_str]
# Show integer
print(num_int)
Output: 👇️
[25, 27, 45, 36, 41, 30]
In this example, we use list comprehension to convert the list of strings num_str to a list of integers num_int. The output shows the list of integers converted from the list of strings using list comprehension.
Conclusion
We can use the map() function or list comprehension to convert a list to an integer in Python. These methods provide a convenient way to handle numeric conversions from lists of strings to lists of integers.