Variable inconsistency in Python?

89
March 20, 2022, at 5:10 PM

I've run into a strange inconsistency. This is a simplified version of the problem:

func1={
    'flist':[12,13,14],
    'fnum':10
}
dlist=func1['flist']
dnum=func1['fnum']
dlist+=[16]
dnum+=1
print(func1)
print(dnum)

The output is:

{'flist': [12, 13, 14, 16], 'fnum': 10}
11

Why is that the changes to the variable dlist are carried over to flist in func1, but changes in dnum are not carried over to fnum in func1?

flist has changed, fnum has not.

Answer 1

This has to do with the mutability of the underlying objects. Since func1['flist'] refers to a list, when you do dlist=func1['flist'] you are actually getting a reference to the memory address of func1['flist'] and then when you add another value, you are modifying the same object in memory. This is because lists are mutable objects and referred to by reference.

On the other hand when you do dnum+=1, what is happening in memory is that 10+1=11 is being created as a new object in memory and then dnum is set to point to the new memory address. This has no effect on the memory address and therefore the value of func1['fnum']. This is the behaviour that happens for immutable types.

Rent Charter Buses Company
READ ALSO
How can create a nested directory?

How can create a nested directory?

What is to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

140
owl carousel stop showing images

owl carousel stop showing images

Add owl carousel css and js:

122
Incremental BR tag counter isn´t working, something is missing

Incremental BR tag counter isn´t working, something is missing

I have the following code, in order to add an incremental counter next to each BR tag, as a per line counter for a lyric song, but it isnĀ“t workingHelp is apreciated!

93
How to add a button to remove user

How to add a button to remove user

I currently have this code that displays users on a team and when you click on the name of a user that is on the list it passes the name that you click to a function which removes them from the teamInstead I would like a button to be next to the name and when you click the button...

90