Hello, I’m new to Sublime and I have this code:
new_list=[]
for number in range(0,2):
colors={'Red':'Green'}
new_list.append(colors)
print(new_list)
for element in new_list[0:1]:
if element['Red']=='Green':
element['Red']='Blue'
print(new_list)
Which results in:
[{'Red': 'Green'}, {'Red': 'Green'}]
[{'Red': 'Blue'}, {'Red': 'Green'}]
So far so good.
But when I write the dictionary outside the for loop:
new_list=[]
colors={'Red':'Green'}
for number in range(0,2):
new_list.append(colors)
print(new_list)
for element in new_list[0:1]:
if element['Red']=='Green':
element['Red']='Blue'
print(new_list)
The result is different:
[{'Red': 'Green'}, {'Red': 'Green'}]
[{'Red': 'Blue'}, {'Red': 'Blue'}]
I realize it matters if the dictionary is written inside or outside the for loop, but why does it result in the way it does? If I tell the program only to check for specific elements in new_list, why does it check for all of them?
Thanks.