Sublime Forum

Dictionary inside or outside a for loop: What makes the difference?

#1

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.

0 Likes

#2

Note this isn’t a forum for general programming help, this is specifically for issues/help with Sublime Text. That being said in the first bit of code each element of the list is a separate dict, whereas in the second they’re all the same one.

0 Likes