David Baldi
David Baldi

Reputation: 13

Getting MemoryError when appending to a list using a for loop

def show_magicians(magicians_list):
    """Print the name of each magician in a list."""
    for magician in magicians_list:
        print(magician.title())

def make_great(magicians_list):
    """Make each magician great again."""
    for magician in magicians_list:
        magician = magician + " " + "the Great"
        magicians_list.append(magician)

list_of_dudes = ['houdini','david blaine','jebus']

make_great(list_of_dudes)

show_magicians(list_of_dudes)

print(list_of_dudes)

Why is the second function not working? I'm trying to change each magician in the list of dudes to "[Magician] the Great" but I keep getting a memory error. Any advice?

Thank you, -confused n00b

Upvotes: 1

Views: 32

Answers (1)

Barmar
Barmar

Reputation: 782107

You shouldn't be appending to the list, you should replace each element with its "great" version.

def make_great(magicians_list):
    """Make each magician great again."""
    for i, magician in enumerate(magicians_list):
        magician = magician + " " + "the Great"
        magicians_list[i] = magician

Your version is appending to the list that it's iterating over. As a result, it never ends, because it continues iterating over the new elements, and makes them even greater (houdini the Great the Great) and then iterates over those elements (houdini the Great the Great the Great) and so on until you run out of memory.

Upvotes: 2

Related Questions