'converting each element from string to int in nested list in python [duplicate]

I have data in python with nested lists, a part of which looks like:

data = [['214', '205', '0', '14', '710', '1813494849', '0'], ['214', '204', '0', '30', '710', '1813494856', '0'], ['214', '204', '0', '34', '710', '1813494863', '0'], ['213', '204', '0', '35', '710', '1813494870', '0'], ['213', '203', '0', '35', '710', '1813494877', '0']]

While converting the data using couple methods:

1.

 new_data_list = [[int(x) for x in list] for list in data]
  1.   list=[]
      for i in range(0,len(data)):
          list.append([])
          for j in range(0,len(data[i])):
              b=int(data[i][j])
              list[i].append(b)
    

I am getting the error which says:

> ValueError: invalid literal for int() with base 10: ''

There are no non-numeric data in my list of data. But there might be something with the header, like an empty header treated as non-numeric value as I have created a list of data from csv.

I wanted to know an efficient way which can convert each element of the list to int while keeping the data multi list.



Solution 1:[1]

Call int for each item in each nested list:

new_list = [[int(x) for x in lst] for lst in nested]

Or using map:

new_list = [list(map(int, lst)) for lst in nested]

Solution 2:[2]

A concise one is:

x = ['123', '12', '5']
r = list(map(int, x))
print(r)
>[123, 12, 5]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 janos
Solution 2 Vivi