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
Converting all strings in list to integers in Python
Sometimes we have a list containing strings that represent numbers. In such cases, we need to convert these string elements into actual integers for mathematical operations or data processing.
Using List Comprehension with int()
The most Pythonic approach uses list comprehension with the int() function to iterate through each element and convert it ?
string_numbers = ['5', '2', '-43', '23']
# Given list
print("Given list with strings:")
print(string_numbers)
# Using list comprehension with int()
integers = [int(i) for i in string_numbers]
# Result
print("The converted list with integers:")
print(integers)
Given list with strings: ['5', '2', '-43', '23'] The converted list with integers: [5, 2, -43, 23]
Using map() Function
The map() function applies the int() function to every element in the list. Since map() returns a map object, we wrap it with list() ?
string_numbers = ['5', '2', '-43', '23']
# Given list
print("Given list with strings:")
print(string_numbers)
# Using map() and int()
integers = list(map(int, string_numbers))
# Result
print("The converted list with integers:")
print(integers)
Given list with strings: ['5', '2', '-43', '23'] The converted list with integers: [5, 2, -43, 23]
Using a For Loop
For more control or when handling potential errors, you can use a traditional for loop ?
string_numbers = ['5', '2', '-43', '23']
# Given list
print("Given list with strings:")
print(string_numbers)
# Using for loop
integers = []
for item in string_numbers:
integers.append(int(item))
# Result
print("The converted list with integers:")
print(integers)
Given list with strings: ['5', '2', '-43', '23'] The converted list with integers: [5, 2, -43, 23]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most Python code |
| map() | Medium | Fastest | Large datasets |
| For Loop | High | Slower | Error handling needed |
Conclusion
Use list comprehension for most cases as it's readable and efficient. Choose map() for better performance with large datasets, or a for loop when you need custom error handling.
