Learning Python - step by step - 4 - lists

/ #Python

In this part of the tutorial series we'll learn about lists. Lists are collections of data like strings, numbers, etc.

What do we need lists for?

A list can be used for a lot of different purposes. We can have a list of phone numbers, users, images, zipcodes, you name it. We can go through a couple of examples which can help us understand how helpful they can be.

Create a new file, write the following content and save it as python2.py (or whatever you want).

users = ['Stein Ove', 'John Doe', 'Jane Doe', 'John Smith']

If you go your command line and execute this file, you should see something like this:

['Stein Ove', 'John Doe', 'Jane Doe', 'John Smith']

It doesn't make much sense to just print the list like this, but it's nice to know that it's possible.

What more can we do with the list?

Let's say that we want to know who the first person in the list is.

# Replace this line:
# Replace with this

If you execute the file now, you should see "Stein Ove" being printed on the screen. "[0]" means that we want the object at index position 0 (which is the first).

As a little side note, if you notice the "#" I used in the code above, these are used for comments. If you try to add "# This is a comment" somewhere in your python file, it will not have any effect because the interpreter doesn't read it.


Just like strings, lists comes with a lot of functionality from the box. Here's a couple of examples:

users = ['Stein Ove', 'John Doe', 'Jane Doe', 'John Smith']<

# .pop() will remove the last object in the list

# .sort() will sort the objects in the list

# .reverse() will reverse the sort order in the list


In this part you learned a little bit about lists. It's kind of overwhelming for a beginner to just sit and read functions and what they do. So in the next part of this tutorial series, we'll start building some more practical examples where we implement what we have learned so far.

When we've built a couple of examples, we will start expanding our knowledge by learning even more of pythons functionality.


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.