Wondering if a dictionary, if included in a loop, is cleared when the loop moves on.
for x in list:
dict_1 = {}
do_some_stuff_here:
continue
Is the dictionary cleared when moving onto the next item in the list?
Wondering if a dictionary, if included in a loop, is cleared when the loop moves on.
for x in list:
dict_1 = {}
do_some_stuff_here:
continue
Is the dictionary cleared when moving onto the next item in the list?
Why don't you just check it?
In [1]: for i in range(5):
...: my_dict = {}
...: my_dict[i] = i+1
...:
In [2]: my_dict
Out[2]: {4: 5}
If you want your dictionary to keep values you have to declare it earlier.
In [5]: my_dict = {}
In [6]: for i in range(5):
...: my_dict[i] = i+5
...:
In [7]: my_dict
Out[7]: {0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
Yes, by the time the loop finishes, the dictionary you initialized inside the loop will be cleared.
If you don't want the dictionary to be constantly cleared, initialize the dictionary outside of the loop.
dict_1 = {}
for x in list:
do_some_stuff_here_with_dict_1:
continue
Here is a comparison between the two:
outside = {} # Outside of loop
for x in range(5):
inside = {} # Inside of loop
outside[x] = 0
inside[x] = 0
print(outside)
print(inside)
Output:
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
{4: 0}
Essentially, each time the loop is run, you are setting the dictionary back to {}. So after the program finishes, your dictionary has only one entry.