1

I have a list of values, titled 'list', with values 23.4158, 25.3817, 26.4629, 26.8004, 26.6582, 27.7, 27.8476, 28.025. Each value is a string, not a float. Thus, I would like to convert this to a list of floats.

When I create a for loop to reassign the strings as floats, using the float() function, within the loops it shows me that the str has been successfully converted to a float. But when I check the type outside the loop, it shows me they are still strings.

for i in list:
    i = float(i)
    print(i,"=", type(i))
print(type(list[0]))

HOWEVER. When I create an empty list (new_list), and append the converted floats into said list, it shows exactly what I want. In other words, the str--->float conversion is successful. Code as such:

new_list = list()
for i in list:
    i = float(i)
    print(i,"=", type(i))
    new_list.append(i)
print(type(new_list[0]))

Why is it that the reassignment does not 'stick' unless the values are appended to new_list? Lists are mutable, so the old list should be able to be modified. Am i missing something?

1 Answers1

2

The reassignment does not "stick" because you are not converting the item inside the list, you are converting i, which is another value inside the loop, completely detached from the list object. You are just converting a new variable i to float, you are not converting the item from within the list. The variable i is a new variable and python just copied the value from the item inside the new variable i. You are not converting the item from the list, you are converting a new variable i that has the same value as the item that the loop is currently at.

If you want to convert the item from withing the list using a for loop, you must target the item itself using its index:

values = [
    "23.4158", "25.3817", "26.4629", "26.8004", "26.6582", "27.7", "27.8476", "28.025"
]

for i in range(len(values)):
    values[i] = float(values[i])

print(values)
print(type(values[0]))

The reason why it works when appending to a list is because you are appending the newly converted i, which indeed, is a float.

I suggest reading the following:

David
  • 624
  • 1
  • 6
  • 21