Introduction to Lists
This tutorial was written for Python pre 3.0. A 3.0+ version of all my Python tutorials is planned.
You know what a list is. I know what a list is. The whole world recognizes what a list is. Why would Python be any different? But Python is different. Working with lists in Python is much easier than working with them in the real world! You’ll see what I mean in just a second. But first, why am I making such a fuss over lists? It turns out that lists are such an integral part of Python that you can’t call Python Python if it didn’t have these lists. At least, that’s my opinion. Let’s begin the tutorial, shall we?
The List Concept
If I were to ask you to make a list of all your favourite foods, you probably wouldn’t have any trouble doing so. At least, I hope you wouldn’t have any trouble, because if you can do this you’ve got the concept down. So what are your favourite foods? Mine are chicken and rice, baklava, sushi, and a good fresh sub. If we share any favourite foods we should totally be friends. Now lets see this in Python.
1 2 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] print myFavFoods |
Notice that each entry is separated by a comma and enclosed in quotation marks. This means that each entry is a string. Entries could also be numbers, but they’ll be strings unless you take away the quotation marks.
So there. A list in Python. It’s really that easy. Now that we have the concept down, I hope that you like the foods I like because I’ll be using them as an example throughout the rest of the tutorial!
Lists and Variables
What’s the difference between the two? Not much, actually. You can think of a list as being a variable with multiple compartments. To see what I mean take a look at the example below.
1 2 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] print myFavFoods[1] |
Run that. What’s the output? Is it really surprising that “baklava” is displayed? I’ll let you in on a little secret right here and now. Computer Scientists and programmers in general love starting from 0. What this means for our example is that 0 is the first element. Actually, 0 is always the first element. 1 is the second element, and since “baklava” is second it was displayed. The code below will show the first element.
1 | print myFavFoods[0] |
There is another way to access elements in a list. We’ve covered loops before, so the next example should be a pleasant surprise.
1 2 3 4 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] for food in myFavFoods: print food |
Pretty neat, huh? We just went through our entire list printing each element.
List Functions
Python also has a lot of really neat built-in functions that make working with lists a breeze. For example, say that we wanted to know the length of our list. It’s four, since there are four items in our list, but I’d rather confirm this with Python.
1 2 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] print len(myFavFoods) |
Okay. Cool. So Python tells me there are four elements as well.
What if we wanted to sort our list? Well, had our list been full of numbers, it would have been quite obvious as to how they could be sorted. When they’re strings on the other hand, what can we sort them by? The answer? Alphabetically.
1 2 3 4 5 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] print "Before sorting, we have: ", myFavFoods myFavFoods.sort() print "After sorting we have: ", myFavFoods |
You’ll notice that baklava is now first, followed by chicken and rice. Sushi and sub also switched despite having their first two letters be the same. They switched because the third letter – a “b” – comes before sushi’s “s”. Pretty cool, eh? Python sorted our list in a matter of milliseconds. It could do this for much longer lists as well. It really puts us to shame. It could take hours for a human to sort a list of a ten thousand things, but Python could do it in a matter of seconds. I told you lists in Python were easier to work with than in real life!
We could also reverse our list just as easily.
1 2 3 4 5 | myFavFoods = ["chicken and rice", "baklava", "sushi", "sub"] print "Before reversing, we have: ", myFavFoods myFavFoods.reverse() print "After reversing we have: ", myFavFoods |
Now all the elements are reversed. So sub is first, followed by sushi, followed by baklava and finally chicken and rice. To bring it back to the original order, just reverse the list again.
We can also insert things into our list. Say that we have just spent all day writing code in the middle of nowhere in some desert. We’re tired, and we’re so hungry that we could eat a hippo. A whole hippo. So lets add “hippo” to our list.
1 2 | myFavFoods.insert(0, "hippo") print myFavFoods |
Using the built-in insert() function, we have added hippo to our list. If you take a look at the list you’ll notice that hippo is the first element. This is because the function insert() takes two parameters. The first one is the index, and the second one is the element. For the first parameter we said 0, and for the second one we put “hippo”.
After finishing the whole hippo, we’re kind of sick. In fact, if someone were to mention hippo we might just throw up. To prevent this from happening we have to get “hippo” off of that list. Pronto!
1 2 | myFavFoods.remove("hippo") print myFavFoods |
There. Gone. Had there been more than one hippo in that list, only the first one would have been removed. That would have meant that we would have needed to run remove() as many times as there were hippos in that list.
Lets test that theory! After taking weeks to digest the hippo and gaining a few pounds, we’re finally hungry again. This time, we’re going to try and eat something a little healthier. Sushi comes to mind! Not only that, but we can load up on sushi, and not eat all that much. So, lets add a bunch of elements at the end of our list, representing sushi.
1 2 3 | myFavFoods.append("sushi") myFavFoods.append("sushi") myFavFoods.append("sushi") |
That looks good to me. You may have guessed that the function append() adds to the end of a list. With all this sushi, it’s hard to keep count as to how many we added. We can use Python to solve this problem!
1 | print myFavFoods.count("sushi") |
That returns 4. Which makes sense. The original sushi, plus the three others we have just added.
Now that we have eaten some sushi, it’s time to return our list back to normal.
1 2 3 | myFavFoods.remove("sushi") myFavFoods.remove("sushi") myFavFoods.remove("sushi") |
remove() only removes the first occurrence of an element. Since there are four “sushi” elements, we need to run remove() three times to bring it back to just one “sushi”.
A Helpful Pointer
You probably noticed that Python has a lot of built-in functions. Functions you wouldn’t have known about. Functions I wouldn’t have known about. So why do we know about them? Surely we can’t be expected to memorize every single built-in function out there. There must be an easier way. And thankfully, there is.
There are two functions and a website that will help you through out your Python journey. But first, we’ll cover the functions.
1 | dir(list) |
If you’re in Python interactive mode, typing this in will give you an overview of Python’s data type, the list. You can replace list with any of Python’s features. You’ll learn more about them later on. But, this overview isn’t too helpful because it only gives you the names of functions. What we need are descriptions. The function below will describe all of the built-in functions we used today, and more.
1 | help(list) |
There is also a website that has comprehensive documentation on the Python language. Just click the link to visit it. It might be overwhelming since you’re just starting out, but it’s probably a good idea to bookmark it.
A Twist
Lists seem pretty basic, but they can get quite complicate. For example, what’s preventing us from having a list in a list? That’s right, nested lists! Is your mind blown yet?
1 | myFavFoods = [] |
In the first element we’ll have my familiar list of favourite foods, and in the next one some of my favourite places to eat.
1 | myFavFoods = [["chicken and rice", "baklava", "sushi", "sub"], ["home", "mountain", "under a tree"]] |
Do note that if we were to remove the first element, the entire list of foods is gone! Python doesn’t care what’s in the element, only that they are elements and will be treated as such. I suggest you play around with this. A good exercise is trying to add an item to my favourite foods. Can you do it?
Conclusion
So there you have it! Lists. And now you’re the master of them. I really do hope that you aren’t just reading. Learning to program isn’t a spectator sport. You should be thinking ahead, copying and pasting code, and changing things around. You really do need to play around with the code and wonder why it runs the way it does depending on what you change. This is the best way to learn and I highly recommend it! With that said, lists are a pretty basic concept, but they are a vital component to Python. Don’t hesitate to comment if you have a question or just something to say! Look forward to the next tutorial which will cover dictionaries.
Comments
could’t comment on functions page so I do it here instead.
really helped me understand functions!
i use python 3 though and the raw_input doesn’t work there, used input() instead and also the print addNums(userNum1, userNum2) had to be changed to print (addNums(userNum1, userNum2))
but thanks for a great tutorial! When comes the next tutorial
?
I believe that raw_input() is now input() in python3. input() used to run the string as python code. To get a simmilar function in py3 you would need to do eval(input(prompt))