Learn Python – Lists and Tuples

Sun Sep 11, 2016 - 1000 Words

Continuing our series on Python, we’re going to look at how we can work with grouped data using two of the data structures in Python: Lists and Tuples.

Goal for this Tutorial:

  • Learn how to store data in Lists.
  • Learn what a Tuple is and how to use it.

Up to this point, we’ve only worked with individual values. Whether it’s been numbers or strings we’ve only worked with 1 or 2 of them at a time. For us to write programs that solve real problems we’ll probably need to work with groups of data.

The Primary Collection: List

The main collection type that we’ll use while programming Python is the list. Let’s open up the REPL and see what they can do.

$ docker run --rm -it python:3.5
>>> my_list = [1, 2, 3, 4]
>>> my_list
[1, 2, 3, 4]

Lists are not limited to holding the same type, but it’s in your best interest to keep them the same. That being said, the following is a completely valid list:

>>> mixed_list = [1, 'a', 2.5, True]
>>> mixed_list
[1, 'a', 2.5, True]

Reading, Adding, and Editing a List

Whenever we create a list, it’s likely that we’ll want to access the information within the list at some point. Let’s first look at how we can access 1 item at a time:

>>> my_list[0] # Index a single element, indexes start at 0 and iterate up.
1
>>> my_list[3]
4
>>> my_list[10] # Using an index that's higher than the length of the list.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Some languages don’t raise errors when you try to access an index that is out of range for an Array/List, but Python does, so be careful.

Besides just accessing one item in a list, we can slice a list to give us a subset of the items. We saw the slice syntax briefly when learning how to reverse a string, but most of the time you’ll use this feature when working with lists.

>>> my_list[1:3] # Includes index 1, up to, but not including index 3.
[2, 3]
>>> my_list[:3] # From the beginning up to index 3.
[1, 2, 3]
>>> my_list[2:] # From index 2 to the end (including the end).
[3, 4, 5]
>>> my_list[::2] # From beginning to end, every other item
[1, 3, 5]

Now we have a better grasp on how to read from a list, but what if we want to add to it or change what’s in it? Adding to a list is easy enough, there’s a method for it:

>>> my_list.append(6)
>>> my_list
[1, 2, 3, 4, 5, 6]
>>> my_list.append(7)
>>> my_list
[1, 2, 3, 4, 5, 6, 7]
>>> len(my_list) # Get the length of the list
7

Our list will grow as we append new data to it, but this will get a little tedious if we need to add many items to it. We were also able to see how long our list had become using the len function. Thankfully, lists support the + operation so we can insert multiple items at once. We’ll reset my_list to equal [1, 2, 3] just so it’s a little short for our examples.

>>> my_list + ['a', 'b', 'c']
[1, 2, 3, 'a', 'b', 'c']
>>> my_list
[1, 2, 3]

Notice that the plus operation returns a different list that contains all of the items, but it does not change the contents of our variable my_list. If we want to store off this new combined list we would have to set assign the result to a variable.

Sometimes you want to replace content within a list. The syntax for assigning values looks like a mix between reading from the list and assigning a variable.

>>> my_list[0] = 'a' # Replacing a single value, at index 0.
>>> my_list
['a', 2, 3]
>>> my_list[1:] = ['b', 'c'] # Replacing a slice
>>> my_list
['a', 'b', 'c']
>>> my_list[:] = [1]
>>> my_list
[1]

Notice that we were able to replace the entire list’s contents by creating a slice from beginning to end and assigning [1] to it. When you are replacing a slice the lengths don’t need to be the same.

Removing an Item from a List

We now know how to create, read from, and update lists, but we need to also know how to remove items from the list. We’ll use a few different ways to remove items, depending on what we’re trying to do. The first one is the method pop:

>>> my_list.pop() # Removes the last item in the list
3
>>> my_list
[1, 2]
>>> my_list.pop(0) # Given an argument removes item(s) at the given indexes
1
>>> my_list
[2]

You can use pop to remove elements at a specific position in the list, or by default it will remove the last item.

Tuples

Lists are flexible and can be changed, they’re what is called “mutable”. Tuples on the other hand will have the same contents and length from the time they are created; we can’t change them. We’ve seen tuples in action a few times before when we’ve used print, here’s an example:

>>> print("There are %s planets and %s." % (8, "Pluto"))
There are 8 planets and Pluto.

The (8, "Pluto") is the tuple. Tuples are similar to lists in that they are what’s known as a “sequence” in Python, but you’ll usually use them the data of different types unlike you normally will with a list. The data within a tuple will normally be accessed by indexing, whereas you’re more likely to iterate over a list.

Recap

Today, we took a look at two of the collection data types that we’ll use in Python. Lists are one of the most used things in all of programming so we’ll need those before we begin writing more complicated programs in Python.