vik1245
vik1245

Reputation: 556

floating a list of strings

I want to ask a question about converting strings into floats in python.

I have the following list:

coordinates_S
>>> ['0.00000000', '0.00000000', '0.10224900']

and I want to convert each item into a decimal using float()

Evidently, float(coordinates_S didn't work:

TypeError: float() argument must be a string or a number, not 'list'

which makes sense.

I tried this however:

flt_coordinates_S = []
    for item in coordinates_S:
        flt_coordinates_S += float(item)

i.e. iterating through each item in the list and it doesn't work. The error given is:

TypeError: 'float' object is not iterable

but I can't seem to understand why. What am I doing wrong here?

I have not found a question that involves iterating items in a list and converting them to a float.

Upvotes: 0

Views: 61

Answers (4)

Alain T.
Alain T.

Reputation: 42133

You could use map to convert all the elements of the list directly into a new list

 flt_coordinates_S = list(map(float,coordinates_S))

Upvotes: 0

Dominic D
Dominic D

Reputation: 1808

The issue is that you used += (used for extending a list with the elements from another list) when you should have used .append() (used for adding a single element to a list). So that's why you get the error, because it thinks float(item) is a list because you've used +=.

coordinates_S = ['0.00000000', '0.00000000', '0.10224900']
flt_coordinates_S = []
for item in coordinates_S:
    flt_coordinates_S.append(float(item))

Alternatively if you want to do it in one line:

coordinates_S = ['0.00000000', '0.00000000', '0.10224900']
flt_coordinates_S = [float(item) for item in coordinates_S]

Upvotes: 3

Vikika
Vikika

Reputation: 318

lst = ['0.00000000', '0.00000000', '0.10224900']
lst_float = [float(i) for i in lst]
print(lst_float)
[0.0, 0.0, 0.102249]

Try this. Issue with your code is +=. This works in case of string or numbers. Not to append elements to list

Upvotes: 1

chepner
chepner

Reputation: 532003

flt_coordinates_S += float(item) is equivalent to flt_coordinates_S.extend(float(item)); += extends a list with the contents of another iterable.

You want to append a float to the list.

flt_coordinates_S = []
for item in coordinates_S:
    flt_coordinates_S.append(float(item))

Upvotes: 3

Related Questions