dict
, list
, set
(and those I've forgotten) are mutable objects.int
, float
, str
, tuple
are immutable objects.In your second example you assign
0
to a name. The term variable is wrong, because it's a name which holds a reference to the object in memory. First the numeric literal is created as new object in memory and the reference to it is assigned to the name.The line
b = a
does following:- Get the reference of the name a
- Assign the reference to b
The line
a = 10
does following:- Create a new
int
with the value 10 in memory. (values from -2 - something are preassigned during interpreter startup)
- Assign the reference to a
- The name a has now the reference to the object which has the value 10
To make a copy from dicts you could use:
my_d1 = {} my_d2 = my_d1.copy()With lists:
my_list1 = list(range(10)) my_list2 = my_list1[:] # get all references from my_list1 and assign them to my_list2There is also the module
copy
with the functions copy
and deepcopy
.The use case for deepcopy is for example to copy a nested list/dict or something else, which holds elements, which are also containers/sequences.
Replacing the content inside a list with new content:
my_list1 = list(range(10)) print(id(my_list1)) my_list1[:] = list(range(20)) print(id(my_list1)) # no change of ID, this means it is still the same objectWith the built-in function
id
you get the virtual memory address back. Same value means same object.If you understood this, you should dig deeper into it.
For example beginners are confused with
is
and ==
.Only use is, if you want to check, if you have the same object.
If you want to check for equality, use
==
.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!