ufiufi
ufiufi

Reputation: 41

List of list, converting all strings to int, Python 3

I am trying to convert all elements of the small lists in the big list to integers, so it should look like this:

current list:
list = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]


for e in list:
    for i in e:
        i = int(i)

new list:
list = [[1,2,3],[8,6,8],[2,9,3],[2,5,7],[5,4,1],[0,8,7]]

Could anyone tell me why doesn't this work and show me a method that does work? Thanks!

Upvotes: 4

Views: 8485

Answers (4)

titiro89
titiro89

Reputation: 2108

Nested list comprehension is the best solution, but you can also consider map with lambda function:

lista = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]

new_list = map(lambda line: [int(x) for x in line],lista)
# Line is your small list.
# With int(x) you are casting every element of your small list to an integer
# [[1, 2, 3], [8, 6, 8], [2, 9, 3], [2, 5, 7], [5, 4, 1], [0, 8, 7]]

Upvotes: 0

user2390182
user2390182

Reputation: 73450

In short, you are not mutating lst:

for e in lst:
    for i in e:
        # do stuff with i

is the equivalent of

for e in lst:
    for n in range(len(e)):
        i = e[n]  # i and e[n] are assigned to the identical object
        # do stuff with i

Now, whether the "stuff" you are doing to i is reflected in the original data, depends on whether it is a mutation of the object, e.g.

i.attr = 'value'  # mutation of the object is reflected both in i and e[n]

However, string types (str, bytes, unicode) and int are immutable in Python and variable assignment is not a mutation, but a rebinding operation.

i = int(i)  
# i is now assigned to a new different object
# e[n] is still assigned to the original string

So, you can make your code work:

for e in lst:
    for n in range(len(e)):
        e[n] = int(e[n])

or use a shorter comprehension notation:

 new_lst = [[int(x) for x in sub] for sub in lst]

Note, however, that the former mutates the existing list object lst, while the latter creates a new object new_lst leaving the original unchanged. Which one you choose will depend on the needs of your program.

Upvotes: -1

janos
janos

Reputation: 124646

You can use a nested list comprehension:

converted = [[int(num) for num in sub] for sub in lst]

I also renamed list to lst, because list is the name of the list type and not recommended to use for variable names.

Upvotes: 10

ForceBru
ForceBru

Reputation: 44828

for e in range(len(List)):
    for p in range(len(List[e])):
        List[e][p] = int(List[e][p])

Or, you could create a new list:

New = [list(map(int, sublist)) for sublist in List]

Upvotes: 1

Related Questions