Convert all strings in a list to int
In Python, you can use the
map() function along with the built-in
int() function to convert all strings in a list to integers. The
map() function applies a given function (in this case
int()) to all elements in an iterable (in this case a list). Here's an example:
string_list = ["1", "2", "3", "4"] int_list = list(map(int, string_list)) print(int_list)
This will convert all elements of the string_list to integers and store it in int_list.
Alternatively, you can use a list comprehension to achieve the same result:
string_list = ["1", "2", "3", "4"] int_list = [int(x) for x in string_list] print(int_list)
This will iterate over each element of the string_list, convert it to int and store the result in a new list int_list.
You can also use
map() function with lambda function to convert the elements of list to integers
string_list = ["1", "2", "3", "4"] int_list = list(map(lambda x: int(x), string_list)) print(int_list)
Please keep in mind that, these methods will raise a
ValueError if any of the elements of the list is not a string representing an integer.