aysh
aysh

Reputation: 599

How to Iterate over the list and convert the datatype

Below is my list

list_a = ['20.3', '6.74', '323','a']

Code is below

try:
    list_a = map(float, list_a)
except ValueError:
    pass
for i in list_a:
    print (i)

Expected result

[20.3, 6.74, 323,'a']

Upvotes: 1

Views: 50

Answers (3)

Deepan
Deepan

Reputation: 430

list_a = ['20.3', '6.74', '323','a']
b=[float(i) if not i.isalpha() else i for i in list_a]
print(b)

This code works fine

Upvotes: 1

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

this cast data according to the datatype looks like

list_a = ['20.3', '6.74', '323', 'a']
result = []
for x in list_a:
    if x.isalpha():
        result.append(x)
    elif x.isdigit():
        result.append(int(x))
    else:
        result.append(float(x))
print(result)

Upvotes: 1

Sanket Singh
Sanket Singh

Reputation: 1346

You can use following:

list_a = ['20.3', '6.74', '323','a']
for i,v in enumerate(list_a):
    try:
        x=float(v)
        list_a[i]=x
    except:
        pass

This would be working for your scenario.

Upvotes: 2

Related Questions