Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary in Python
#2
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:
  1. Get the reference of the name a
  2. Assign the reference to b

The line a = 10 does following:
  1. Create a new int with the value 10 in memory. (values from -2 - something are preassigned during interpreter startup)
  2. Assign the reference to a
  3. 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_list2
There 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 object
With 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!
Reply


Messages In This Thread
Dictionary in Python - by kartheek - Dec-03-2019, 10:45 AM
RE: Dictionary in Python - by DeaD_EyE - Dec-03-2019, 12:58 PM
RE: Dictionary in Python - by kartheek - Dec-07-2019, 12:29 PM
RE: Dictionary in Python - by snippsat - Dec-07-2019, 01:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert List of Dictionary to dictionary of dictionary list in python kk230689 2 51,229 Apr-27-2019, 03:13 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020