0

I need to know why the following two blocks of code return different outputs. I have:

somelist = ['foo', 'bar']
somelist.append('baz')
print somelist

prints ['foo', 'bar', 'baz'] as expected. However,

print ['foo', 'bar'].append('baz')

prints None. Thanks in advance!

EDIT: Thanks all. Is there a way to use the append function and print command in one line of code?

prgrmr
  • 55
  • 1
  • 4
  • 1
    Well.... `.append` returns `None` and `print ['foo', 'bar'].append('baz')` prints whatever `.append` returns. – Felix Kling Feb 23 '13 at 02:03
  • Or this one: http://stackoverflow.com/questions/1682567/why-does-pythons-list-append-evaluate-to-false – mgilson Feb 23 '13 at 02:08

2 Answers2

2

.append on a list mutates the list. Since it is mutating the list, python takes the convention that the function should return None to make it explicitly clear that the function's purpose is to change it's arguments (in this case, the list instance bound that the method is bound to).

mgilson
  • 300,191
  • 65
  • 633
  • 696
2

list.append is an in-place operation, meaning that it returns None, but it alters the actual list itself.

Volatility
  • 31,232
  • 10
  • 80
  • 89