Why and When do we use an empty lists or dictionary?

Hi,
I have a general question. Sometimes we use an empty list or empty dictionary while working in for loop. My question is why and when do we use them?
Thank you,
Hossain

Hi @hossainms2017,

We use an empty list or dictionary in combination with a loop, when we need to fill this list (dictionary) with values based on the calculations or conditions of the loop .

First, we create an empty list (or dictionary). Then we use a loop to iterate over a sequence of values. With each iteration, and if the conditions inside the loop are satisfied, we add a new value to our list (or dictionary) which initially was empty.

For adding a new value to the list we use the method append().

For adding a new value to the dictionary, we insert a new index key into the dictionary, then we assign it a new value:

dictionary[key] = value

Hope it was helpful.

1 Like

To complete the response from @Elena_Kosourova, note that if the key is not already in the dictionary, we get an error. With a defaultdict from collections module, we can initiate a dictionary and iterate over a sequence of values without worrying the key already exists or not. When you have to iterate over a very large over amount of values, it is crucial.

Hi @hossainms2017

Adding to @Elena_Kosourova’s concise answer

Try to think about what would happen if you are not creating an empy list/dictionary first outside the loop. Let’s look at the append() method first:

# !Warning! This code doesn't run
for i in range(10):
    miss_list.append(10)

This results in a **NameError** : name 'miss_list' is not defined because Python cannot find our miss_list variable. No surprise here, we cannot add an element to nothing. The same happens, if you try to add strings to a list using the + Operator (Only for illustration purposes, allways use append() in your code for adding an element to a list via a for-loop)

# !Warning! This code doesn't run
for e in ['a', 'b', 'c']:
    miss_list += e

Takeaway: With for-loops you cannot create a list variable on the fly (when you try to add the first element). It needs to be created separatly.

Best
htw

@WilfriedF

We actually only get an error if we try to increment the value of a key, which is not already in the dict. This works everytime

dictionary[key] = value

This, however, only works if the key is already in the dictionary

dictionary[key] += 1

When this statement is written in the long from it is clear why. (You need to access the corresponding value in the dict. first to increment it by 1)

dictionary[key] = dictionary[key] + 1 

This is where defaultdict() indeed comes in handy. Example below.

# Option 1
word_counts = {}
word_list # list with many words

for e in word_list():
    if e in word_counts:
        word_counts[e] += 1
    else:
        word_counts[e] = 1

# Option 2 (better, more concise)
word_counts = defaultdict(int) # default value of int is 0
word_list # list with many words

for e in word_list():
    word_counts[e] += 1

Best
htw

1 Like

Thanks @htw ! You explained it better than me, but basically that’s the point I wanted to highlight (it costs me a bit to write in English language, so sometimes I make it very short, maybe too much!).