Most elegant way to modify elements of nested lists in place Most elegant way to modify elements of nested lists in place python python

Most elegant way to modify elements of nested lists in place


for row in table:    row[1:] = [int(c) for c in row[1:]]

Does above look more pythonic?


Try:

>>> for row in table:...     row[1:]=map(int,row[1:])... >>> table[['donkey', 2, 1, 0], ['goat', 5, 3, 2]]

AFAIK, assigning to a list slice forces the operation to be done in place instead of creating a new list.


I like Shekhar answer a lot.

As a general rule, when writing Python code, if you find yourself writing for i in range(len(somelist)), you're doing it wrong:

  • try enumerate if you have a single list
  • try zip or itertools.izip if you have 2 or more lists you want to iterate on in parallel

In your case, the first column is different so you cannot elegantly use enumerate:

for row in table:    for i, val in enumerate(row):        if i == 0: continue        row[i] = int(val)