0

If I were to have the following list:

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']

how would I convert all possible items into either ints or floats accordingly, to get

lst = [3, 7, 'foo', 2.6, 'bar', 8.9]

thanks in advance.

3
  • 1
    Loop over each item and make an attempt to convert. If the conversion fail then ignore the item. Commented Jan 25, 2018 at 11:07
  • use a foreach, iterate over all items. try convert item to int, catch error then ignore it (or nest another try) then repeat for the whole list. do some research on documentations! Commented Jan 25, 2018 at 11:08
  • 2
    FWIW, it's generally not a great idea to have a mixture of datatypes in a list. Code to process such lists tends to get messy and require explicit type testing which goes against Python's duck-typing philosophy. Commented Jan 25, 2018 at 11:20

2 Answers 2

8

Loop over each item and make an attempt to convert. If the conversion fail then you know it's not convertible.

def tryconvert(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
newlst = [tryconvert(i) for i in lst]
print(newlst)

Output:

[3, 7, 'foo', 2.6, 'bar', 8.9]
Sign up to request clarification or add additional context in comments.

1 Comment

This is great, perfect example of EAFP
0

Try something like this :

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']

for j,i in enumerate(lst):
    if i.isdigit():
        lst[j]=int(i)
    elif '.' in i:
        lst[j]=float(i)

output:

[3, 7, 'foo', 2.6, 'bar', 8.9]

1 Comment

This is going to fail if the list contains a string like 'A.B'

Your Answer

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