0

In python i would like to convert some string elements of a list to int.

So i have:

my_list = ["car", "10", "20", "50", "60", "13", "bike"]

How to make it:

my_list = ["car", 10, 20, 50, 60, 13, "bike"]

2 Answers2

6

A simple comprehension will do:

my_list = [int(x) if x.isdigit() else x for x in my_list]

This uses a conditional expression and tests with str.isdigit.

The str.isdigit check does assume that all numbers are non-negative integers. For more complex numerical strings like "-5" or "1.7" you might have to be more verbose and use a loop and possibly a broader type (float) in line with @Sujay's solution.

user2390182
  • 72,016
  • 6
  • 67
  • 89
2
for i, j in enumerate (my_list):
    try:
         my_list[i]=int(j)
    except ValueError:
          pass