Big Sharpie
Big Sharpie

Reputation: 849

How do i change a list element's value in a for loop in python?

I am having a bit of trouble changing the values of list elements when utilizing a for loop. The following code outputs 10 and 5 - but I'm expecting 10 and 10.

amount = 5
costFieldList = [amount]

for index, field in enumerate(costFieldList):
    if type(field) is int:
        costFieldList[index] = field*2
        print(costFieldList[index])
print(amount)

Is this an issue of scope? Thanks in advance.

Upvotes: 0

Views: 97

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

If you want to set both amount and costFieldList[index] to field * 2 use:

amount = 5
costFieldList = [amount]

for index, field in enumerate(costFieldList):
    if isinstance(field,int):  # use issinstance to check if field is an integer
        costFieldList[index] = field * 2
        print(costFieldList)
        amount=costFieldList[index] # set amount to value of costFieldList index 
print(amount,costFieldList ) 
(10, [10])

Upvotes: 1

Artjom B.
Artjom B.

Reputation: 61892

By writing costFieldList[index] = field*2, you are creating an entirely new int instance which then overwrites the "reference" to the instance in the array, but not the value itself. So you lose the reference to the original value of amount.

At this stage amount still has a "reference" to 5 which is why you get 5 as the second output.

Upvotes: 1

Joe
Joe

Reputation: 2437

You are printing amount at the end. This is set to an immutable value (5).

If your last line is print(costFieldList), you will see that it is [10] as expected. You used amount to initialize the list, but there is no link back to modify amount.

Upvotes: 1

Related Questions