Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python 3: Why does .append() work in the scenario instead of the second?

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])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading