0

Why does

num_list = [1, 2, 3, 4, 5]
first_num = num_list[0]
first_num = 0
print(num_list)

returns [1, 2, 3, 4, 5], but

dict_list = [{"num": 1}, {"num": 2}, {"num": 3}, {"num": 4}, {"num": 5}]
first_dict = dict_list[0]
first_dict["num"] = 0
print(dict_list)

returns [{'num': 0}, {'num': 2}, {'num': 3}, {'num': 4}, {'num': 5}]?

In other words, why assigning a variable to a list element, and modifying that variable, would cause that element to be modified only if it's a dict and not a number? I think this might be due to the way numbers and dictionaries are stored in Python, but being a Python beginner, I'm not sure sure where to look for an answer.

I'd really appreciate your help for me to understand this distinction!

seismatica
  • 437
  • 1
  • 6
  • 19
  • @vaultah IMO the answers to the linked question are lacking a sufficient explanation. (and they even admit it: *I'm glossing over a few details here for simplicity -- e.g. what happens when you assign to a list element*) – mkrieger1 Sep 22 '17 at 16:14
  • 1
    This is a good article about the topic: https://nedbatchelder.com/text/names.html – mkrieger1 Sep 22 '17 at 16:21
  • 1
    Basically, `varname = something` will always change what the variable `varname` points to. However, `varname['key'] = something` will always call `varname.__setitem__(key, something)`. As a Python beginner this is the most important part of the difference, since it lets you know when something is being modified and when it isn't. For example, if you used `first_dict = {'num': 0}`, the `dict` in `dict_list` would *not* be modified. – Jeremy McGibbon Sep 22 '17 at 16:22
  • The website that mkrieger1 referenced and the answer by Jeremy McGibbon explained my question perfectly! Thanks guys! – seismatica Sep 22 '17 at 17:23

0 Answers0