Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to convert list with str into list with int?

What is the easiest way to convert list with str into list with int in Python? For example, we have to convert ['1', '2', '3'] to [1, 2, 3]. Of course, we can use a for loop, but it's too easy.

like image 776
user285070 Avatar asked Mar 11 '10 11:03

user285070


People also ask

How do you convert a string to an int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you convert a string to a list of numbers in Python?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.


1 Answers

Python 2.x:

map(int, ["1", "2", "3"])

Python 3.x (in 3.x, map returns an iterator, not a list as in 2.x):

list(map(int, ["1", "2", "3"]))

map documentation: 2.6, 3.1

like image 188
codeape Avatar answered Sep 21 '22 18:09

codeape