Search code examples
pythonlistinputglobal-variables

How to add elements to the already existing elements instead of overwriting them in a list?


I have this code here:

def alist():
    wor = []
    definition = []
    wele = str(input("Enter a word: "))
    dele = str(input("Enter a definition: "))
    x = wor.append(wele)
    y = def.append(dele)
    print("Words' List: ", wor, "\nDefinitions' List: ", definition)

Whenever I run it, I can add elements to the lists wor and def, however, whenever I run it again, it overwrites the elements I added earlier when I ran it the first time. I have avoided this problem by turning wor and def into global variables. Is there any other method other than making the two lists into global variables?

Thanks!


Solution

  • You're creating new, empty lists each time you call the function. The function should take the lists as parameters and modify them.

    def alist(wlist, dlist):
        wele = input("Enter a word: ")
        dele = input("Enter a definition: ")
        wlist.append(wele)
        dlist.append(dele)
    
    word_list = []
    def_list = []
    
    word_count = int(input("How many words are you defining? "))
    for _ in range(word_count):
        alist(word_list, def_list)
    print("Words' List: ", word_list, "\nDefinitions' List: ", def_list)
    

    Making the lists parameters allows you to have multiple word lists, e.g.

    spanish_words = []
    spanish_defs = []
    alist(spanish_words, spanish_defs)
    

    However, it's generally poor design to keep related data in separate lists, which you have to keep in sync. It would be better to use a single list of dictionaries or tuples, so all the related items (e.g. the word and its definition) are together.