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)
5
  • 4
    What is wrong with your current solution? Commented Mar 8, 2014 at 17:09
  • possible duplicate of Convert all strings in a list to int Commented Mar 8, 2014 at 17:11
  • @Torxed no it is not a duplicate. Commented Mar 8, 2014 at 17:14
  • Just keep in mind that having a multi-type list (i.e. a list with more than one type of variables) is considered a bad practice and it would not work in many other programming languages :) Cheers, Alex Commented Mar 8, 2014 at 17:14
  • 1
    @mbatchkarov: the obvious thing wrong with the questioner's code is that they say they want to convert elements 1 to 2, but the code actually converts elements 1 to 3 ;-) Commented Mar 8, 2014 at 18:03

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Haha, i was 5 seconds to late :) +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.