2

I have the following python code:

def make_great(l):
    l = ['The great ' + magician for magician in l]

magicians = ['Tom']
make_great(magicians)
print(magicians)

The print statement prints the original list, not the one modified by the make_great() function. I was trying to figure out a way of modifying each element of a python list without explicitly accessing it's index and then reassigning that index a new value. Wouldn't the magicians list now point to the new list formed by the comprehension based on Python's memory model ? I am guessing that I am not getting the desired results because this is a scoping issue ? But when I pass in magicians , it replaces l in the function argument so the python interpreter actually sees magicians = ['The ... ?

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • The problem is that you're modifying the local variable `l` to refer to a new object. Instead, you should modify the object referred to by `l`. –  Feb 26 '16 at 00:33
  • I'm confused, when I use the index notation, `l[i]` to modify the list, why is that not considered a local variable, but when I use the `=` operator to reassign `magicians` to a new list, it's now considered local ? – Mutating Algorithm Feb 26 '16 at 00:39
  • @MutatingAlgorithm considering renaming `l` variable name to `lst` or other better readable name as it prevents confusion with number `1`. – Jan Vlcinsky Feb 26 '16 at 00:54

3 Answers3

3

When you assign it to l, you are redefining l, not modifying it. Use l[:] instead:

def make_great(l):
    l[:] = ['The great ' + magician for magician in l]

You could also return the list and redefine magicians:

def make_great(l):
    return ['The great ' + magician for magician in l]

magicians = ['Tom']
magicians = make_great(magicians)
print(magicians)

In that case, you could assign magicians to make_great(['Tom']):

magicians = make_great(['Tom'])
print(magicians)
zondo
  • 19,901
  • 8
  • 44
  • 83
0

Your function is not returning anything. You can either have your print statement in the function or return the modified list and then print it

Bob Ezuba
  • 510
  • 1
  • 5
  • 22
0
def make_great(l):
    return ['The great ' + magician for magician in l]

magicians = ['Tom']
magicians = make_great(magicians)
print(magicians)

The make_great function duplicates your array, so you need to return and assign the result to magicians.

You can check How do I pass a variable by reference? for passing reference or values in functions

Community
  • 1
  • 1
jood
  • 2,188
  • 2
  • 21
  • 32