Home > Blockchain >  How to make changes to a list permanently in Python
How to make changes to a list permanently in Python

Time:11-28

I need help with debugging this code. The program should modify the list (magicians) by adding the phrase "the Great" after each item. Call show_magicians() to see that the list has actually been modified.

#Add 'Great' suffix to magician names
def make_great(magicians):
  print("Greatifying Magicians...")
  magicians = ['{0} the Great'.format(mag) for mag in magicians]

#Display magician names
def show_magicians(magicians):
  for magician in magicians:
    print(magician)

magicians = ["Andrea Haddad", "Shroomy", "Arkos Martinez"]
make_great(magicians)
show_magicians(magicians)

Show_magicians() should print the list's items followed by 'the Great'. However, this is the output I am met with.

Greatifying Magicians...
Andrea Haddad
Shroomy
Arkos Martinez

CodePudding user response:

In place modification

magicians[:] = ['{0} the Great'.format(mag) for mag in magicians]

In place modification is required to actually change the values. When you use the equals assign, it creates a new variable altogether, which we do not want. While this may seem awkward, putting the [:], it means we are actually assigning to the list itself rather than creating a new instance. You can research this further:

Here: https://datatofish.com/modify-list-python/

and get some practice:

Here: https://leetcode.com/problems/remove-element/

CodePudding user response:

You must return the value of the make_great function then assign a variable to it.

def make_great(magicians):
  print("Greatifying Magicians...")
  magicians = ['{0} the Great'.format(mag) for mag in magicians]
  return magicians

#Display magician names
def show_magicians(magicians):
  for magician in magicians:
    print(magician)

magicians = ["Andrea Haddad", "Shroomy", "Arkos Martinez"]
magicians = make_great(magicians)
show_magicians(magicians)

Output:

Greatifying Magicians...
Andrea Haddad the Great
Shroomy the Great
Arkos Martinez the Great
  • Related