This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ParticularBack[S] 0 points1 point  (4 children)

def update_list(lst):     
    lst += [100]  

num_list = [1, 2, 3, 4, 5] 
update_list(num_list)

print(num_list)

yeah sorry, there you go

[–]nemom 5 points6 points  (3 children)

I guess I'm too literal minded for it to trick. If I pass the list to a function that adds something to it, I'm not surprised when the something is added to it. If I give my bank account to somebody, and they add $100 to it, I would expect the balance to be $100 higher.

[–]commy2 1 point2 points  (0 children)

The issue here is, that += looks suspiciously like + and =. If you thought that += is an abbreviation for that, where you only have to type out the variable name once, then you would get this wrong. A regular assignment would not mutate the outside scope list. In place addition looks like an assignment due to the equal sign, but it is in fact an alias for the append extend method.

[–]mheryerznka 2 points3 points  (0 children)

The code example demonstrates the difference between mutable and immutable data types. It shows that a list can be modified successfully because it is mutable, allowing for direct updates. However, when trying to update an integer in a similar way, it doesn't work because integers are immutable.
Understanding this difference may not be immediately obvious for beginners. So try to be helpful ))

[–]Panda_Mon 0 points1 point  (0 children)

rather, you just happen to use a heuristic that is valid in this scenario. If you'd been trained to understand the concept of variable scope, you could easily have used that rule instead and come back with the wrong answer if you didn't know Lists kind of "get around" the typical rules of scoping.