List manipulation in functions


#1

How is this wrong...? And more importantly...WHY? :rage::tired_face::triumph::persevere:

ERROR MESSAGE:

Oops, try again. list_extender([1, 2, 3, 4]) returned None, did you remember to return the result?

CODE:

n = [3, 5, 7]
def list_extender(lst):
    lst = lst.append(9)
    return lst 

print list_extender(n)

#2

Remove the lst = in lst = lst.append(9). I'm not sure why myself but when I removed lst =, it worked. Hopefully someone can shed more light about this.


#3

Thanks @datfatcat. Yes, 1/ that worked and 2/ An explanation would be great.

Here's how I understand it so far, but would be great to see a more eloquent explanation

Essentially, we were both assigning the Return object to it's own method. The only thing we should be assigning a list to is its own similar datatype.

If we want to access a method, we should just call that method within the code.


#4

So your confusion arises from the idea that we need to explicitly point at the lst when changing it.

If we break it down we see that .append() is a function that acts on the list is it attached to. So lst.append(9) is saying "add a 9 to the end of lst". So by adding lst= to the front you are saying

lst="add a 9 to the end of lst" or lst=the action of appending the list.

This can be compared to a real life example.
We have a shoe as our object (the list) and tie as our function.

shoe.tie() would mean we are going to tie that shoe (in python syntax). That has all the info we need to know that we edited the shoe by tying the laces.

shoe=shoe.tie() is saying that the shoe is equal to the tying of said shoe. Shoe is something (a noun), while shoe.tie is an action (verb/function). So the whole thing errors out because you were trying to equate something with an action done to itself.


#5

Kudos to you! This is a good explanation :slight_smile: I really like it.


#6

Thank you @austink26, this was a great explanation and analogy to understand! Appreciate it very much


#7

That is a super helpful analogy. Thank you!


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.