1
def foo(i, x=[]):
    x.append(x.append(i))
    return x
for i in range(3):
    y = foo(i)
    print(y)
print(y)

this results in

[0, None]
[0, None, 1, None]
[0, None, 1, None, 2, None]
[0, None, 1, None, 2, None]

Why is the None being appended in the list? I checked some threads on this topic, unfortunately I couldn't still understand why None is being printed.

If I replace x.append(x.append(i)) with just x.append(i) the None goes away. That made sense, but I'm still unclear why the x.append(x.append(i)) adds a None.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Ajay Pai
  • 53
  • 1
  • 6
  • 1
    Possible duplicate of [Why does append return none in this code?](http://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code) – zondo Apr 17 '16 at 22:30
  • What is the expected behavior of `x.append(x.append(i))`? – BallpointBen Apr 17 '16 at 23:27

2 Answers2

1

Alecxe is correct. To summarize, append(value) does not have a return value, and will thus return None. If you wish to append with a return value in a semi-pythonic manor, use: y = x = x + [value] this will set y equal to x with value appended in both.

However, in addition to that, part of the problem is that you are using a default argument that is mutable. This means that every time you call the function with the default value of x, the list, x will be the same it was when the last call finished. Consider the following

def add(num, x=[]):
    x.append(num)
    print x

Calling add(4) will print [4], then calling add(5) after will print [4, 5]

I hope this helps.

Henry
  • 41
  • 5
  • thanks a lot. i ran the code . i see that print x will give a list as you described. thanks – Ajay Pai Apr 17 '16 at 22:49
  • Great answer! didn't realise a default could mutate like that. Could you please make this answer complete by also summarising @alecxe's answer too? I realised otherwise this is better as a comment (but I realise you don't have comment anywhere yet). – user161778 Apr 18 '16 at 03:10
0

That's because the .append() method appends to a list and returns None:

>>> x = []
>>> print(x.append(1))
None

In other words, the inner x.append(i) would append i and the outer would append None.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195