How to clear a List in Python. Why clearing a List deletes copies of it in other variables
August 18, 2024
Why clearing a List in Python deletes copies of it in other variables
Clearing a list in Python can be done in a number of ways, some of which can lead to unexpected results if you don't know the differences and what's going on under the hood.
Let's look at a very simple script that doesn't do anything meaningful, but will demonstrate what I mean:
temp_list = list() dict_config = dict() for l in ['a', 'b', 'c']: for n in range(1,4): temp_list.append(l + str(n)) dict_config[l] = temp_list temp_list.clear() print(dict_config)
This script creates a list and a dictionary. It then runs two loops, one of which is nested. The nested loop fills in a list, then appends that list to the dictionary (using one of the iterables as a key). The temporary list is cleared so that it can be used again and again in the same loop, but with different data.
What output do you expect?
According to the author of the script, the result should be a dictionary with the following contents:
{'a': ['a1', 'a2', 'a3'], 'b': ['b1', 'b2', 'b3'], 'c': ['c1', 'c2', 'c3']}
But what is actually obtained when executing the script?
The result obtained:
{'a': [], 'b': [], 'c': []}
That is, the dictionary is indeed created, it has keys, but the values (which should have been temporary lists) are empty.
This example is an adaptation of a script fragment with a more meaningful function. But, in any case, lists can be used as temporary storage for dynamic data, so we need to figure out what exactly the problem is.
There is no logical error in the script – the problem is in the way the list is cleared.
How to clear a list in Python
Lists in Python can be cleared in several ways, which cause 2 possible options:
1) One of the methods works “in-place”, that is, it clears those memory cells in which the contents of the list are stored). Even after the list is saved to the dictionary as a value, the dictionary does not store a duplicate of the information from the list, but a reference to the memory area where the list is located. This leads to the fact that if the list is cleared, it is also cleared in the dictionary, since this is not duplicate data, but just a reference to the memory area in which there is now nothing.
2) The second method of clearing simply creates a new list object and assigns it to a variable with the same name (the same variable). With this method of clearing, the list previously saved to the dictionary is unaffected.
Let's consider the same script, in which the line
temp_list.clear()
is replaced by the line:
temp_list = []
That is, the assignment of a new empty value is selected as the clearing method.
temp_list = list() dict_config = dict() for l in ['a', 'b', 'c']: for n in range(1,4): temp_list.append(l + str(n)) dict_config[l] = temp_list temp_list = [] print(dict_config)
In this case, the script will work as expected.
Clearing a list in-place and creating a new list (reinitialization)
So, there are the following ways to clear a list “in-place”:
temp_list.clear() del temp_list[:] temp_list*=0
When using these methods of clearing a list, the memory areas in which the list is stored are cleared, and copies of the list that are references to this memory area are also cleared.
And there is one way to delete a list using reinitialization:
temp_list = []
Re-creating a list with the same name does not lead to the loss of copies of the list stored in other variables.
Related articles:
- How to run a program from Python: how to run a system command or another Python script (complete guide) (100%)
- How to add a ‘b’ prefix to a variable name in Python? (100%)
- How to run small Python code in Bash (75.7%)
- ONVIF client with command line interface (75.7%)
- How to convert a string to uppercase in Bash (75.7%)
- How to reboot a server in DigitalOcean (RANDOM - 50%)
