6

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Side note: *never* shadow built-in `list`, e.g. use `L` or `list_` instead. – jpp Jan 09 '19 at 11:30
  • There is nothing wrong with either method that you showed, fundamentally. The problem is that your **actual** data contains empty strings (`''`), which **cannot be converted to `int` individually** like this. – Karl Knechtel Apr 04 '23 at 05:23

2 Answers2

7

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]
janos
  • 120,954
  • 29
  • 226
  • 236
  • I tried this but it shows this error: ValueError: invalid literal for int() with base 10: '' – The Novice Programmer Nov 26 '17 at 07:50
  • @TheNoviceProgrammer it looks like there's a non-numeric value in your input. You should have mentioned that in the question. So now, what would you like to do with non-numeric values? – janos Nov 26 '17 at 07:53
  • There are no non-numeric values in my data. I think it might me the header which is not visible in the list, as I have created the list of data using readcsv – The Novice Programmer Nov 26 '17 at 08:05
  • @TheNoviceProgrammer in `data` in the question, there are no non-numeric values, and you should not get any `ValueError`. – janos Nov 26 '17 at 08:32
0

A concise one is:

x = ['123', '12', '5']
r = list(map(int, x))
print(r)
>[123, 12, 5]
Vivi
  • 4,070
  • 6
  • 29
  • 44
user1767754
  • 23,311
  • 18
  • 141
  • 164