6

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?

Martin Dimitrov
  • 349
  • 1
  • 3
  • 11

4 Answers4

15

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
julienc
  • 19,087
  • 17
  • 82
  • 82
6

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?

Community
  • 1
  • 1
Checkmate
  • 1,074
  • 9
  • 16
5

enumerate would be the best thing to do in this case, then modify the value at each index in the array.

for i, magician in enumerate(magicians):
    magicians[i] = "the Great " + magician
Ryan
  • 14,392
  • 8
  • 62
  • 102
2

You can do this with a little Python magic combining lambda and map together

>>> magicians = ['hudini', 'angel', 'teller', 'anderson', 'copperfield']
>>> map(lambda el:'pre_'+el,magicians)
['pre_hudini', 'pre_angel', 'pre_teller', 'pre_anderson', 'pre_copperfield']

Try it out here

loretoparisi
  • 15,724
  • 11
  • 102
  • 146