Majed Saaeddin
Majed Saaeddin

Reputation: 81

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!

Upvotes: 0

Views: 74

Answers (2)

Barmar
Barmar

Reputation: 782166

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.

Upvotes: 2

whege
whege

Reputation: 1441

When you append to your lists you assign it to new variables, x an y, but you never do anything with those. wor and def never change. You actually don't have to assign append() to a new variable, it will happen in-place.

If you want your two lists to always retain their memory of what they contain every time the function is called, then you should define them outside the scope of the function, otherwise every time you call the function you re-initiate them as empty lists.

l1 = []
l2 = []

def alist():
     wele = str(input("Enter a word: "))
     dele = str(input("Enter a definition: "))
     l1.appnd(wele)
     l2.append(dele)
     print("Words' List: ", l1, "\nDefinitions' List: ", l2)

Upvotes: 0

Related Questions