Reputation: 1120
Why does the following code give 'None'? How can I resolve this?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
What also doesn't work:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
Upvotes: 3
Views: 208
Reputation: 336228
It depends on what you want to do. If you want list1
to have changed after a call to f1
, use
def f1(list1):
list1.append(2)
f2(list1)
See what happens:
>>> l = [1]
>>> f1(l) # Modifies l in-place!
[1, 2]
>>> l
[1, 2]
If you don't want list1
to be changed:
def f1(list1):
f2(list1 + [2])
Now see this:
>>> l = [1]
>>> f1(l) # Leaves l alone!
[1, 2]
>>> l
[1]
Upvotes: 6
Reputation: 879849
In general, Python methods that mutate an object (such as list.append
, list.extend
, or list.sort
) return None
.
If you wish to print out the new list:
def f1(list1):
list1.append(2)
f2(list1)
Upvotes: 7