Video Pending

Created by Zed A. Shaw Updated 2024-02-17 04:54:36
 

42: Doing Things to Lists

You have learned about lists. When you learned about while-loops you "appended" numbers to the end of a list and printed them out. There were also Study Drills where you were supposed to find all the other things you can do to lists in the Python documentation. That was a while back, so review those topics if you do not know what I'm talking about.

Found it? Remember it? Good. When you did this you had a list, and you "called" the function append on it. However, you may not really understand what's going on so let's see what we can do to lists.

When you write mystuff.append('hello') you are actually setting off a chain of events inside Python to cause something to happen to the mystuff list. Here's how it works:

  1. Python sees you mentioned mystuff and looks up that variable. It might have to look backward to see if you created it with =, if it is a function argument, or if it's a global variable. Either way it has to find the mystuff first.
  2. Once it finds mystuff it reads the . (period) operator and starts to look at variables that are a part of mystuff. Since mystuff is a list, it knows that mystuff has a bunch of functions.
  3. It then hits append and compares the name to all the names that mystuff says it owns. If append is in there (it is), then Python grabs that to use.
  4. Next Python sees the ( (parenthesis) and realizes, "Oh hey, this should be a function." At this point it calls (runs, executes) the function just like normally, but instead it calls the function with an extra argument.
  5. That extra argument is ... mystuff! I know, weird, right? But that's how Python works, so it's best to just remember it and assume that's the result. What happens, at the end of all this, is a function call that looks like: append(mystuff, 'hello') instead of what you read, which is mystuff.append('hello').

For the most part you do not have to know that this is going on, but it helps when you get error messages from Python like this:

Previous Lesson Next Lesson

Register for Learn Python the Hard Way, 5th Edition (2023-2024)

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.