0

I'm learning Python 3 through Codecademy and am struggling to understand the difference between these bits of code:

def append_size(lst):
  lst.append(len(lst))
  return lst

vs

def append_size(lst):
  return lst.append(len(lst))

Both functions are called with print(append_size([23, 42, 108])

Why does the first work (prints [23, 42, 108, 3]) and the second returns 'None'?

Elfayylmao
  • 11
  • 1

2 Answers2

2

This happens because when you append() something to a list nothing is returned. It simply appends the item to the list and returns None if you print it. Eg:

l = [1,2,3]
print(l.append(4))
None

In this case, 4 is getting appended to a list called l. The simple task of append is adding the item to the list at the end. Hence, when you do print(l.append(4)) it says None.

But if you try:

l = [1,2,3]
l.append(4)
print(l)
[1, 2, 3, 4]

Here it prints the value of the list l after 4 is appended.

Abhyuday Vaish
  • 2,272
  • 5
  • 9
  • 24
0

Okay so the append function is used to add an item to an existing list.

Suppose I have a list a = [1,2,3] and I want to add 4 to the list. I'll do a.append(4) and would get the desired output of [1,2,3,4].

In the first append_size function the code firstly appends an item to the original list and then returns the list that's why you get a list output of [23, 42, 108, 3]. But in the second function the code returns lst.append and not any list. Because the append function always has the value None, it returned None as the output.

Zero
  • 1,541
  • 1
  • 3
  • 13
  • Okay wicked, this makes a lot more sense for me now, thank you so much for the help :) I spent a long time being confused about `.append()`, but I guess I didn't realise `.append()` has no inherent value and I was calling `.append()` rather than the updated list – Elfayylmao Apr 28 '22 at 08:59
  • @Elfayylmao I like how you use "wicked" as an expression. And good luck coding! – Zero Apr 28 '22 at 09:01