0

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.

6
  • 1
    You're printing the list element, not the list itself. You have replaced the element, but the old one is still in scope, and that's what you're printing. Try print(costFieldList) instead. Commented Jun 11, 2014 at 14:59
  • 1
    Is this an issue of scope sort of. You print amount which is still 5. You change the value of 5 that is in the list, but that is not what you print at the end Commented Jun 11, 2014 at 14:59
  • Basically, I want amount to now have twice its original value so that print(amount) outputs 10. How would I go about doing that? Commented Jun 11, 2014 at 15:04
  • 1
    dont use type(field) is int use isinstance(field, int) Commented Jun 11, 2014 at 15:17
  • It doesn't make sense to also update amount inside the loop. You don't need a loop if you have only one value. You can change the value before creating the list. Or if you have multiple values in the list, then you should know how you want to update amount. Most people cannot read minds. Commented Jun 11, 2014 at 15:51

3 Answers 3

1

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.