I want to make a function that adds a specific word in front of every string in the array. At the end I want the array changed. I have this code:
def make_great(magicians):
"""Change magicians"""
for magician in magicians:
magician = "the Great" + magician
magicians = ["hudini", "angel", "teller", "anderson", "copperfield"]
make_great(magicians)
print(magicians)
This code doesn't change the array. How can I make my function work?
You can use enumerate
to loop over the list with both the index and the value, then use the index to change the value directly into the list:
def make_great(magicians):
for index, magician in enumerate(magicians):
magicians[index] = "the Great " + magician
When you use a for-each loop:
def make_great(magicians):
for magician in magicians:
magician = "The Great" + magician
you're actually creating a new string magician; so modifying it won't modify the original array as you found.
Instead, iterate over the items in the array:
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = "The Great" + magicians[i]
Or use an enumerator as proposed above. See: How to modify list entries during for loop?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With