Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - How to modify a string in an array? [duplicate]

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?

like image 767
Martin Dimitrov Avatar asked Jun 28 '16 19:06

Martin Dimitrov


2 Answers

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
like image 156
julienc Avatar answered Nov 20 '22 12:11

julienc


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?

like image 6
Checkmate Avatar answered Nov 20 '22 13:11

Checkmate