1

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?

  • 5
    It isn't "cleared". A *new* (empty) dictionary is created each turn through the loop. – khelwood Mar 15 '18 at 13:56
  • 3
    At the beginning of each iteration of the loop, `dict_1 = {}` will be executed, creating an empty dictionary. After the loop ends, `dict_1` will still exist, with all the data you added to it in the final loop iteration. – Patrick Haugh Mar 15 '18 at 13:56
  • 2
    Not only cleared but overwritten by an empty one. – Alexander Ejbekov Mar 15 '18 at 13:57

2 Answers2

3

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}
gonczor
  • 3,994
  • 1
  • 21
  • 46
0

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.

kale
  • 151
  • 1
  • 10