import random
rand_list = []
rand_dict = {}
for i in range(1, 10):
for j in range(1, 3):
rand_list.append(random.randint(1, 10))
rand_dict.update({i: rand_list.copy()})
rand_list.clear()
print(rand_dict)
Dictionaries store references to some variables rather than the actual value, there for a clear()
would affect the dictionary as well. (If I would try to go into the world of theory, this is what you'd call mutable variables. Lists being one of those. While a variable with a integer would be copied rather than references)
Instead, make a copy of it before you wipe it. That way any modifications to the original value won't affect the dict. Or rethink your approach.
One other approach that @deceze points out, which is a more traditional way of solving this is putting the list creation in the loop.
import random
rand_dict = {}
for i in range(1, 10):
rand_list = []
for j in range(1, 3):
rand_list.append(random.randint(1, 10))
rand_dict.update({i: rand_list.copy()})
print(rand_dict)
That way, each iteration is a new instance of a list. Essentially doing the same thing as clearing it. My terminology might be off here tho, I'm more of a practitioner/dabbler than a theoretician.
One useful tool to see why this happens, and why the last approach works, is by doing:
for i in range(1, 10):
rand_list = []
print(hex(id(rand_list))) # <--
This prints the memory address of the variable. If it stays the same after each clear()
or value in the dict, you know it's a referenced value.