NotASuperSpy
NotASuperSpy

Reputation: 53

Is there a way to replace variables in for loops?

I am trying to create a for loop like this:

list = [a, b, c, a_1, b_1, c_1]
for i  in list:
    if str(i).endswith(".0"):
        i = int(i)
print(type(a))

This outputs:

<class 'float'>

This means that the for loop didn't define the entry into an integer. I checked if this works to make sure it was the for loop:

if str(i).endswith(".0"):
    i = int(i)

Does anyone know why the for loop wouldn't define the variable the same as outside of the loop? Any help would be appreciated.

Upvotes: 1

Views: 1054

Answers (2)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15558

You cannot assign a value to floats object. What you are trying to do is:

# something like
# assume  i = 5.0
# if str(i).endswith('.0'):
#    i = int(i)
# if str(5.0).endswith('.0'):
#      5.0 = 5 

# what you want

list_ = [a, b, c, a_1, b_1, c_1]
for index, value  in enumerate(list_):
    if str(value).endswith(".0"):
        list_[index] = int(value)

a, *rest = list_
print(type(a))

Note: list is python keyword. Avoid overriding it.

demo

list_ = [1.0, 2, 1, 5.0]
for index, value  in enumerate(list_):
    if str(value).endswith(".0"):
        list_[index] = int(value)

a, *rest = list_
print(type(a))
# class 'int'>

Upvotes: 1

Oli
Oli

Reputation: 2602

The reason a is not being edited is that i is first assigned to the same value as a, then i is assigned to a different value without modifying a. Python has no way to get references to variables so that they can be edited. One workaround is to use indirection: create an object with an attribute to store the value, then i will point to the same object as a, and modifying the attribute of the object modifies both a.value and i.value:

from dataclasses import dataclass
from typing import Any

@dataclass
class Box:
    value : Any

# note that the values are constructed like `Box(0.2)`
a, b, c, a_1, b_1, c_1 = (Box(i/10) for i in range(6))


list = [a, b, c, a_1, b_1, c_1]
for i  in list:
    if str(i.value).endswith(".0"):
        i.value = int(i.value)
print(type(a.value))

Upvotes: 1

Related Questions