so the code is
magician_names = ['Elon musk', 'Neuralink', 'Neuralink']
def show_magicians(names):
print("each object/person in the list:\n")
for name in names:
print(name.title())
def make_great(list):
for q in list:
q = 'the Great ' + q.title()
make_great(magician_names)
print(magician_names)
You are just reassigning the loop variable q
, not actually mutating the list:
def make_great(list):
for q in list:
q = 'the Great ' + q.title()
# q is now a different new str object, but list is unchanged
do instead:
def make_great(lst): # also do not shadow the built-in list
for i in range(len(lst)):
lst[i] = 'the Great ' + lst[i].title()
Above answer is also right, you are not mutating list I ll try to clarify some things let us see what is happening see the comment
magician_names = ['Elon musk', 'Neuralink', 'Neuralink'] #declared a list
def show_magicians(names): #defined a function though never called
print("each object/person in the list:\n")
for name in names:
print(name.title())
def make_great(list): # defined a function
for q in list: #iterated on list
q = 'the Great ' + q.title() # stored a result into memory never used or printed it or returned anything
make_great(magician_names) #called the function operated on list never printed it but it worked in memory
print(magician_names)
In simple words if you have Dog Maxi(suppose a function) in a room unless you call Maxi it wont come to you. But Maxi will stay in room show_magicians here. You called the Maxi and told him to say woof woof silently so you never heard him but Maxi said and did his job (like no print statement here).
Tried putting in real world analogy hope that helps
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.