-1
lis = [1,2,3]

print(lis.append(4))
# Returns None

#############

lis = [1,2,3]

lis.append(4)

print(lis)
# Returns [1,2,3,4]

I found this code here but I don't understand the reasoning why .append() returns None. The person who answered said it was because

.append() changes the list in place and returns None.

But this doesn't make sense to me. The way I interpret the sample code blocks above is simply that you must first append to the list before you can rpint it, but then this goes against my understanding of order of evaluation when evaluating statements within statements.

Community
  • 1
  • 1
whatwhatwhat
  • 1,352
  • 2
  • 25
  • 42
  • 2
    What's not to understand? The linked question that you quote explains it perfectly. The append statement is evaluated, *and returns None*. Meanwhile, the list is mutated. – Daniel Roseman Jan 07 '17 at 20:09
  • 1
    `append` is not a mathematical function which returns anything. It is a set of instructions that mutates the object itself. What would you expect as result? –  Jan 07 '17 at 20:09
  • 3
    what part of the order of evaluation seems troublesome according to you? `print(lis.append(4))` first evaluates `lis.append(4)` to `None` which is then printed. – Dimitris Fasarakis Hilliard Jan 07 '17 at 20:11
  • Oh ok. Sorry, new to Python! – whatwhatwhat Jan 07 '17 at 20:12
  • If 5 people gave me *the same* answer, is the question actually "unclear"? – whatwhatwhat Jan 07 '17 at 20:15
  • what what what is your question? This may help: http://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code – Chris_Rands Jan 07 '17 at 20:21

2 Answers2

1

A data type of the type list is mutable, means you can change the object directly without replacing it.

This quality allows for methods like append, extend and more to give their print.

When methods like that are called on an object, they actually change the referenced object, but returns nothing (None), because the functionality we need them for is changing the object, not returning output.

When you evaluate print(lis.append(4)), the interpreter calls lis.append(4) that changes lis and returns None. Now, it moves to print the evaluated expression - print(None), and that's what you get.

Uriel
  • 14,803
  • 6
  • 23
  • 46
-1

When using the append method it acts on lis and appends to it. It acts on lis by reference, not by copy.

oliversm
  • 1,489
  • 4
  • 17
  • 41