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 was 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 go find in the book where you did that and review 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 type Python code that reads 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:
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:
$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Thing(object): ... def test(hi): ... print "hi" ... >>> a = Thing() >>> a.test("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: test() takes exactly 1 argument (2 given) >>>
What was all that? Well, this is me typing into the Python shell and showing you some magic. You haven't seen class yet but we'll get into that later. For now you see how Python said test() takes exactly 1 argument (2 given). If you see this it means that Python changed a.test("hello") to test(a, "hello") and that somewhere someone messed up and didn't add the argument for a.
That might be a lot to take in, but we're going to spend a few exercises getting this concept firm in your brain. To kick things off, here's an exercise that mixes strings and lists for all kinds of fun.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.append(next_one) print "There's %d items now." % len(stuff) print "There we go: ", stuff print "Let's do some things with stuff." print stuff print stuff[-1] # whoa! fancy print stuff.pop() print ' '.join(stuff) # what? cool! print '#'.join(stuff[3:5]) # super stellar!
$ python ex38.py Wait there's not 10 things in that list, let's fix that. Adding: Boy There's 7 items now. Adding: Girl There's 8 items now. Adding: Banana There's 9 items now. Adding: Corn There's 10 items now. There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] Let's do some things with stuff. Oranges Corn Corn Apples Oranges Crows Telephone Light Sugar Boy Girl Banana Telephone#Light