简体   繁体   中英

How to make changes to a list permanently in Python

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM