Cannot append to a returned list?

前端 未结 4 1890
南旧
南旧 2021-01-21 19:36
def f():
    lst = [\'a\', \'b\', \'c\']
    return lst[1:]

why is f().append(\'a\') is None == True even though f().__class__

相关标签:
4条回答
  • 2021-01-21 19:57

    In this context it's always good to be fully aware of the difference between expressions and commands. There are basically two ways to append a value x to a list l

    1. Using a command: l.append(x). Usually a command doesn't return any value; it performs some kind of side-effect.
    2. Using an expression, namely l+[x] which stands for a value and does nothing. I.e. you assign l=l+[x]
    0 讨论(0)
  • 2021-01-21 20:10

    Because append() modifies the list, but does not return it.

    0 讨论(0)
  • 2021-01-21 20:12

    Try this:

    f()+['a']
    

    Hope this helps

    0 讨论(0)
  • 2021-01-21 20:19

    Because append() returns None and not the list object. Use

    l = f()
    l.append('a')
    ...
    
    0 讨论(0)
提交回复
热议问题