Sometimes you want to change the type of each of the elements inside the list. For example, you want to convert a list of strings to ints in python. Then How you can do so? In this entire tutorial, you will learn the various ways to convert a list of strings to ints in python.
Methods to Convert list of Strings to Ints in Python
In this entire section, you will know the various examples of the conversion of elements of string type to int type.
Method 1: Convert list of Strings to Ints in Python using the map function
The first method is the use of map function in python. It accepts two arguments the first one is the type and the second one is the list. In our case, the type is the int.
Execute the below lines of code for the conversation.
my_list = ["1","2","3","4","5"] results = list(map(int,my_list)) print(results)
Method 2: Using List comprehension
The second method to convert list of strings to ints is list comprehension. List comprehension allows you to create and define lists using existing lists. List comprehension works faster than the normal functions and loops are used to create lists.
Use the below lines of code.
my_list = ["1","2","3","4","5"] results = [int(i) for i in my_list] print(results)
The list comprehension will loop around each element of the string elements and convert each element into an integer.
Method 3: Using Custom function
You can also define a custom function that will convert strings to ints in python. Inside the function, I will use the for loop and the append() function and return the converted list.
Execute the below lines of code.
def conv_str_to_int(myList): b= for i in myList: b.append(int(i)) return b my_list = ["1","2","3","4","5"] converted_list = conv_str_to_int(my_list) print(converted_list)
These are the methods for Converting list of Strings to Ints in Python. You can choose any methods you want. But I suggest you to chose those functions that less time for conversion. The first method takes less time as compared to the other methods. I hope this tutorial has solved your queries on how to do a Conversion of list of Strings to Ints in Python. Even if you have doubts then you can contact us for more help.