Home > Software design >  Python - change a list column type without creating a new list
Python - change a list column type without creating a new list

Time:06-03

I have lists within the list and for the third column in each sub-list I would like to change its value from String to Int, without creating additional new list (I would know how to do this if I declare new list list2) but to change it immediately within it (if possible).

list1=[[1,"a","100"],[2,"b","200"],[3,"c","300"]]    
[int(item[2]) for item in list1]                
for t in list1:
    print(type(t[2]))

<class 'str'>
<class 'str'>
<class 'str'>

This prints str. The goals is to have integers. Also I must use python 2.7 (can't upgrade to python 3)

The goal is to have list with all other columns:

list1=[[1,"a",100],[2,"b",200],[3,"c",300]] 

CodePudding user response:

list1=[[1,"a","100"],[2,"b","200"],[3,"c","300"]]
for x in list1:
    x[2] = int(x[2])
list1 # outputs [[1, 'a', 100], [2, 'b', 200], [3, 'c', 300]]
  • Related