Modifying a list in python by passing it to a function

后端 未结 3 1032
心在旅途
心在旅途 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:47

    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

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-22 03:59
    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

    0 讨论(0)
提交回复
热议问题