Python – Convert List of strings into List of integers

Python – Convert List of strings into List of integers

To convert a given list of strings into a list of integers in Python, you can use List comprehension or For loop to iterate over the elements, and then use int() built-in function to convert each string element to an integer element.

Now, we shall go through some examples of converting a given list of strings into list of integers using list comprehension, or a For loop.

1. Converting list of strings into list of integers using List comprehension and int()

Consider that we are given a list of string elements, and we have to convert them into a list of integers using List comprehension and int() builtin function.

Steps

  1. Given a list of strings in my_list.
  2. Use list comprehension, and for each element in the original list, apply int() function to the element.
[int(x) for x in my_list]
  1. The above expression returns a list of integers created from the original list. You may store it in a variable, say list_int.
  2. You may print the resulting integer list to the standard output using print() statement.

Program

The complete program to convert the given list of strings into a list of integers using List comprehension and int() built-in function.

Python Program

# Given a list of strings
my_list = ['10', '20', '30', '40']

# Convert list of strings into list of integers
list_int = [int(x) for x in my_list]

print(list_int)
Run Code Copy

Output

[10, 20, 30, 40]

2. Converting list of strings into list of integers using For loop and int()

Consider that we are given a list of string elements, and we have to convert them into a list of integers.

Steps

  1. Given a list of strings in my_list.
  2. Take an empty list to store the resulting list of integers, say list_int.
  3. Use a For loop to iterate over the given list, and for each element in the given list, convert the string element into an integer element, and append the integer element to list_int using list append() method.
for item in my_list:
  list_int.append(int(item))
  1. After the For loop is done, list_int contains the respective integer values created from the original list.

Program

The complete program to convert the given list of strings into a list of integers using For loop, list append() function, and int() built-in function.

Python Program

# Given a list
my_list = ['10', '20', '30', '40']

# Take an empty list to store the integers
list_int = []

# Convert list of strings into list of integers
for item in my_list:
    list_int.append(int(item))

print(list_int)
Run Code Copy

Output

[10, 20, 30, 40]

Summary

In this tutorial, we have seen how to convert a given list of strings into a list of integers, with examples.

Related Tutorials

Code copied to clipboard successfully 👍