2
def f():
    lst = ['a', 'b', 'c']
    return lst[1:]

why is f().append('a') is None == True even though f().__class__ is <type 'list'> and f() == ['b', 'c']

1

4 Answers 4

11

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

l = f()
l.append('a')
...
1
  • 4
    +1: This requires a #StdPython_2 kind of answer. Methods which mutate an object (almost) never return a value. pop() is the notable exception.
    – S.Lott
    May 13, 2011 at 18:57
2

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

1

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

Try this:

f()+['a']

Hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.