Skip to content

Lists

Introduction

In Python, a container is a type of data structure that holds and organizes multiple values or objects. Containers are used to store collections of elements, allowing you to group related data together for easier management and manipulation. Python provides several built-in container types, each with its own characteristics and use cases. In this first section, we cover list objects, followed by dictionaries and tuples.

What is a list?

A list is a collection of items. You can make a list including the letters of the alphabet or the digits from 0 to 9. You can put anything you want into a list and the items in your list don’t have to be related in any particular way.

Because a list usually contains more than one element, it’s a good idea to use the plural for a variable of type list, such as letters, digits, or names.

A list is created with an opening and closing square bracket []. Individual elements in the list are separated by commas. Here’s a simple example of a list:

beatles = ["John", "Paul", "George", "Ringo"]
print(beatles)
>>> Output
['John', 'Paul', 'George', 'Ringo']
print(type([]))  # print the type of an empty list
>>> Output
<class 'list'>

Accessing elements

You can access any element in a list by using the index of the desired item. To access an element in a list, write the name of the list followed by the index of the item enclosed in square brackets. For example, let’s pull out the first Beatle in beatles:

beatles = ["John", "Paul", "George", "Ringo"]
print(beatles[0])
>>> Output
John

IndexError

Info

In Python, index positions start at 0, not 1. This is true for most programming languages. If you’re receiving unexpected results, determine whether you are making a simple off-by-one error.

beatles = ["John", "Paul", "George", "Ringo"]
print(beatles[4])

... results in

Traceback (most recent call last):
  File "<ipython-input-7-68dd8df4c868>", line 2, in <module>
    print(beatles[4])
          ~~~~~~~^^^
IndexError: list index out of range

... since there is no official 5th Beatle.

There is a special syntax for accessing the last element in a list. Use the index -1 to access the last element, -2 to access the second-to-last element, and so on.

beatles = ["John", "Paul", "George", "Ringo"]
print(beatles[-1])  # Ringo
print(beatles[-2])  # George
Indexing

Define a list that stores following programming languages:

  • R
  • Python
  • Julia
  • Java
  • C++

and use print() to output: "My favourite language is Python!"

List manipulation

Python provides several ways to add or remove data to existing lists.

Adding elements

The simplest way to add a new element to a list, is to append it. When you append an item to a list, the new element is added at the end.

numbers = [1, 2, 3]
print(numbers)
numbers.append(4)
print(numbers)
>>> Output
[1, 2, 3]
[1, 2, 3, 4]

The append() method makes it easy to build lists dynamically. For example, you can start with an empty list and then add items by repeatedly calling append().

numbers = [1.0, 2.0, 0.5]
numbers.append(4.0)
numbers.append(3.0)
numbers.append("one hundred")

print(numbers)
>>> Output
[1.0, 2.0, 0.5, 4.0, 3.0, 'one hundred']

Up until now, our lists contained only one type of elements - strings or integers. However, as in the example above, you can store multiple different types of data in a list. Moreover, you can do nesting (for example, you can store a list within a list - more on that later). Hence, lists can represent complex data structures. Nevertheless, don't mix and match every imaginable data type within a single list (just because you can) as it makes the handling of your list quite difficult.

Info

Later, we will learn how to perform the same task without repeatedly calling the same append() method over and over.

Inserting elements

You can add a new element at any position in your list by using the insert() method. You do this by specifying the index of the new element and the value of the new item.

pokemon = ["Charmander", "Charizard"]
pokemon.insert(1, "Charmeleon")
print(pokemon)
>>> Output
['Charmander', 'Charmeleon', 'Charizard']

Removing elements

To remove an item from a list, you can use the remove() method. You need to specify the value which you want to remove. However, this will only remove the first occurrence of the item.

pokemon = ["Charmander", "Squirtle", "Charmeleon", "Charizard", "Squirtle"]
pokemon.remove("Squirtle")
print(pokemon)
>>> Output
['Charmander', 'Charmeleon', 'Charizard', 'Squirtle']

Popping elements

Sometimes you’ll want to use the value of an item after you remove it from a list. The pop() method removes a specified element of a list. Additionally, the item is returned so you can work with that item after removing it.

The term pop comes from thinking of a list as a stack of items and popping one item off the top of the stack. In this analogy, the top of a stack corresponds to the end of a list.

pokemon = ["Charmander", "Charmeleon", "Bulbasaur", "Charizard"]
bulbasaur = pokemon.pop(2)
print(pokemon)
print(bulbasaur)
>>> Output
['Charmander', 'Charmeleon', 'Charizard']
Bulbasaur
List manipulation

Define a list with a couple of elements (of your choice). Play around with the methods append(), insert(), remove() and pop(). Print the list after each operation to see the changes.

Organizing a list

For various reasons, often, your lists will be unordered. If you want to present your list in a particular order, you can use the method sort(), or the function sorted().

sort()

The sort() method operates on the list itself and changes its order.

numbers = [5, 4, 1, 3, 2]
numbers.sort()  # sort in ascending order
print(numbers)

numbers.sort(reverse=True)  # sort in descending order
print(numbers)
>>> Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

sorted()

The sorted() function maintains the original order of a list and returns a sorted list as well.

numbers = [5, 4, 1, 3, 2]
sorted_numbers = sorted(numbers)

print(f"Original list: {numbers}; Sorted list: {sorted_numbers}")
>>> Output
Original list: [5, 4, 1, 3, 2]; Sorted list: [1, 2, 3, 4, 5]

Length

You can easily find the length of a list with len().

print(len([3.0, 1.23, 0.5]))
>>> Output
3

Slicing

To make a slice (part of a list), you specify the index of the first and last elements you want to work with. Elements up until the second index are included. To output the first three elements in a list, you would request indices 0 through 3, which would return elements 0, 1, and 2.

players = ["charles", "martina", "michael", "florence", "eli"]
print(players[0:3])
>>> Output
['charles', 'martina', 'michael']
Slicing

Define a list of your choice with at least 5 elements.

  • Now, perform a slice from the second up to and including the fourth element.
  • Next, omit the first index in the slice (only omit the number!). What happens?
  • Lastly, re-add the first index and omit the second index of your slice. Print the result.

Copy

To copy a list, you can use the copy() method.

original_list = [1, 2, 3]
copied_list = original_list.copy()

# perform some changes to both lists
original_list.append(4)
copied_list.insert(0, "zero")

print(f"Original list: {original_list}, Copied list: {copied_list}")
>>> Output
Original list: [1, 2, 3, 4], Copied list: ['zero', 1, 2, 3]

Be careful!

You might wonder why we can't simply do something along the lines of copied_list = original_list. With lists, we have to be careful, as this syntax simply creates a reference to the original list. Let's look at an example:

original_list = [1, 2, 3]
copied_list = original_list

# perform some changes to the original list
original_list.append(4)

print(f"Original list: {original_list}, Copied list: {copied_list}")

which leaves us with:

>>> Output
Original list: [1, 2, 3, 4], Copied list: [1, 2, 3, 4]

As you can see, the changes to the original list are reflected in the copied one. You can read about this in more detail here.

Note

We can actually check whether both lists point to the same object in memory by using id() which returns the memory address of an object. Just remember, to be careful when copying lists and check if your program behaves as intended!

original_list = [1, 2, 3]
copied_list = original_list

print(id(original_list) == id(copied_list))  # True
Unknown method

Use the given list (don't worry about the syntax, it's just a short expression to create a huge list):

long_list = [True] * 1000
  • Check the length of the list.
  • Apply a method that deletes all elements in the list and returns an empty list []. You might need to use Google, since it is a method not previously discussed.
  • Check the length of the list again.

Recap

We extensively covered lists and their manipulation.

  • Accessing elements with indices (including slicing)
  • The IndexError
  • Adding elements with append() and insert()
  • Removing elements with remove() and pop()
  • Sorting with sort() and sorted()
  • Length of a list with len()
  • Make a copy with copy()