Convert all strings in a list to int
In Python, I want to convert all strings in a list to integers.
How do I make it:
10 Answers 10
Use the map function (in Python 2.x):
In Python 3, you will need to convert the result from map to a list:
![]()
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = [‘1′,’2′,’3’]
It’ll give you output like
![]()
![]()
If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well — you can leverage your own function with errorhandling:
To also handle iterables inside iterables you can use this helper:
![]()
A little bit more expanded than list comprehension but likewise useful:
There are several methods to convert string numbers in a list to integers.
In Python 2.x you can use the map function:
Here, It returns the list of elements after applying the function.
In Python 3.x you can use the same map
Unlike python 2.x, Here map function will return map object i.e. iterator which will yield the result(values) one by one that’s the reason further we need to add a function named as list which will be applied to all the iterable items.
Refer to the image below for the return value of the map function and it’s type in the case of python 3.x

The third method which is common for both python 2.x and python 3.x i.e List Comprehensions
Python | Преобразование всех строк в списке в целые числа
Взаимопревращение между типами данных облегчается библиотеками python. Но проблема преобразования всего списка строк в целые числа довольно распространена в области разработки. Давайте обсудим несколько способов решения этой конкретной проблемы.
Метод № 1: Наивный метод
Это наиболее общий метод, который поражает любого программиста при выполнении такого рода операций. Просто зацикливание по всему списку и преобразование каждой строки списка в int путем приведения типа.
# Python3 код для демонстрации
# преобразование списка строк в int
# используя наивный метод
test_list = [ ‘1’ , ‘4’ , ‘3’ , ‘6’ , ‘7’ ]
# Печать оригинального списка
print ( «Original list is : » + str (test_list))
# используя наивный метод для
# выполнить преобразование
for i in range ( 0 , len (test_list)):
test_list[i] = int (test_list[i])
# Печать измененного списка
print ( «Modified list is : » + str (test_list))
Метод № 2: Использование понимания списка
Это всего лишь своего рода копия описанного выше метода, реализованная с использованием понимания списка, своего рода сокращения, которое разработчик всегда ищет. Это экономит время и сложность кодирования решения.
# Python3 код для демонстрации
# преобразование списка строк в int
# использование списка понимания
test_list = [ ‘1’ , ‘4’ , ‘3’ , ‘6’ , ‘7’ ]
# Печать оригинального списка
print ( «Original list is : » + str (test_list))
# используя понимание списка для
# выполнить преобразование
test_list = [ int (i) for i in test_list]
# Печать измененного списка
print ( «Modified list is : » + str (test_list))
Способ № 3: Использование map()
Это самый элегантный, питонский и рекомендуемый метод для выполнения этой конкретной задачи. Эта функция предназначена исключительно для такого рода задач и должна использоваться для их выполнения.
# Python3 код для демонстрации
# преобразование списка строк в int
# используя карту ()
Python | Converting all strings in list to integers
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem.
Method #1 : Naive Method
This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting.