Please explain why c = None
in the following Python 3 example, from the Python command line.
>>> a = [1,2]
>>> b = a
>>> c = b.append(3)
>>> print(a,b,c)
[1, 2, 3] [1, 2, 3] None
Please explain why c = None
in the following Python 3 example, from the Python command line.
>>> a = [1,2]
>>> b = a
>>> c = b.append(3)
>>> print(a,b,c)
[1, 2, 3] [1, 2, 3] None
list.append()
appends the entry in place and returns nothing which Python takes as None
(default behavior of Python). For example:
>>> def foo():
... print "I am in Foo()"
... # returns nothing
...
>>> c = foo() # function call
I am in Foo()
>>> c == None
True # treated as true
You are assigning the return value of append
which is None
.
>>> a = [1,2]
>>> b = a.append(3)
>>> b == None
True
>>>
The function append doesn't return anything, that's why you have none in the variable. Let's see it better with a little example:
Let's say you have this function
def foo:
bar = "Return this string"
return bar
x = foo()
print(x) # x will be "Return this string"
Now let's say you have this function instead
def foo(bar):
print(bar)
x = foo(33) # Here 33 will be printed to the console, but x will be None
This happens because the return statement on the function, if you don't have any, the function will return None.
append
is a function to do something in the list that you're calling it in (in Python strings are lists too), and this function doesn't need to return anything, it only modifies the list.