Modifying a list in python by passing it to a function

后端 未结 3 1031
心在旅途
心在旅途 2021-01-22 03:21

I have the following python code:

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

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


        
3条回答
  •  时光说笑
    2021-01-22 03:58

    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)
    

提交回复
热议问题