1

Suppose you have a list like:

[["a", "1", "2", "3"], ["b", "4", "5", "6"], ["c", "7", "8", "9"]]

And I want to convert the elements from index 1 to 2 of every sublist into integers as you can see they are themselves strings. Is it possible? If it is, then what is the shortest way to do it? What have I done uptil now is this:

lists = [["a", "1", "2", "3"], ["b", "4", "5", "6"], ["c", "7", "8", "9"]]
for l in lists:
    l[1:4] = [int(x) for x in l[1:4]]
print(lists)
Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113

1 Answers1

4

If you want to convert the lists inplace, your code is good enough.

BTW, the list comprehension can be replaced with map:

l[1:4] = map(int, l[1:4])
falsetru
  • 357,413
  • 63
  • 732
  • 636