Cannot append to a returned list?
def f():
lst = ['a', 'b', 'c']
return lst[1:]
why is f().append('a') is None == True
even though f().__class__
is <type 'list'>开发者_JAVA技巧
and f() == ['b', 'c']
Because append()
returns None
and not the list object. Use
l = f()
l.append('a')
...
Because append()
modifies the list, but does not return it.
Try this:
f()+['a']
Hope this helps
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
- Using a command:
l.append(x)
. Usually a command doesn't return any value; it performs some kind of side-effect. - Using an expression, namely
l+[x]
which stands for a value and does nothing. I.e. you assignl=l+[x]
精彩评论