Search code examples
pythonlistpersistence

Persistent increase of a python list size after every code execution


My code starts with an empty list:

l = []

Let us say I want to append 5 elements to my list every time I run my code:

l += [0, 0, 0, 0, 0]  
print(l) . # reuslt is l = [0, 0, 0, 0, 0]

After the code execution, this information is lost. I want to know how can my list keep growing by five zeros every time I run my code again.

first run >>> [0, 0, 0, 0, 0]
second run >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
third run >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.
.
.

Solution

  • You need to persist the data between runs. One way of doing this is by using the pickle module, which I will demonstrate here as it is very simple. An alternative would be using JSON. These methods can save (or serialise) a Python data object. This is different from just writing text to a text file.

    import pickle
    
    my_list = [0, 0, 0, 0, 0]
    
    # Save my_list
    file = open("save.txt", "wb") # "wb" means write binary (as opposed to plain text)
    pickle.dump(my_list, file)
    file.close()
    
    # Close and restart your Python session
    
    file = open("save.txt", "rb") # "rb" means read binary
    new_list = pickle.load(file)
    file.close()
    
    print(new_list) # -> [0, 0, 0, 0, 0]
    

    Edit: You stated that you want the additions to the list to happen automatically every time the code is run. You could achieve this by appending after loading and then saving again.

    import pickle
    
    # Create an empty list
    my_list = []
    
    # Try to load the existing list in a try block in case the file does not exist:
    try:
        file = open("save.txt", "rb") # "rb" means read binary
        loaded_list = pickle.load(file)
        file.close()
        my_list += loaded_list
    except (OSError, IOError):
        print("File does not exist")
    
    # Append to the list as you want
    my_list += [0, 0, 0, 0, 0]
    
    # Save the list again
    file = open("save.txt", "wb")
    pickle.dump(my_list, file)
    file.close()
    
    print(my_list) # This will get bigger every time the script in run