Lesson 06 - Introduction to Lists

The following topics are discussed in this notebook:

  • Defining lists.
  • Accessing list elements.
  • Updating, adding, and deleting elements.

Lists

A list is a tool for storing a sequence of values. The individual values contained within a list are called the elements or items of the list.

To define a list in Python, we write the elements of the list between a pair of square braces, separated by commas.In the cell below, we create a list containing strings representing the names of each of the eight planets in our solar system. We will store the list in the variable planets.

In [1]:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

List objects have a data type, just like every other object in Python. In the following cell, we check the type of planets.

In [2]:
type(planets)
Out[2]:
list

We can also print lists.

In [3]:
print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Accessing List Elements

Elements in a list are assigned an order when the list is defined, and each element being assigned a numerical position called an index. The first element is assigned an index of 0, the second element is assigned an index of 1, the third element is assigned an index of 2, and so on.

Assume you have a list called my_list, and you wish to access an element whose index is stored in a variable i. This can by done using the following code: my_list[i].

In [4]:
# Print the 1st element of planets
print(planets[0])
Mercury
In [5]:
# Print the 3rd element of planets
print(planets[2])
Earth
In [6]:
# Print the 8th element of planets
print(planets[7])
Neptune

We will get an error if we try to access a list element that does not exist.

In [7]:
print(planets[8])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-c5c892610201> in <module>
----> 1 print(planets[8])

IndexError: list index out of range

We can also access elements of a list by counting from the end of the list. This is accomplished through the use of negative indices. The last element in the list is a index -1, the second to last is at index -2, and so on.

In [8]:
# Print the last element of planets.
print(planets[-1])
Neptune
In [9]:
# Print the 3rd from last element of planets. 
print(planets[-3])
Saturn

In the cell below, write two lines of code that each print out "Mars". Use a positive index in the first line and a negative index in the second line.

In [10]:
print(planets[3])
print(planets[-5])
Mars
Mars

Types of List Elements

While a list object is of data type list, the individual elements of a list will each have their own data types. For example, the elements of the elements of planets list we defined previously are all of type str.

In [11]:
print(type(planets))
print(type(planets[4]))
<class 'list'>
<class 'str'>

It is possible to create lists that contain other data types. The following list contains elements of type int.

In [12]:
pi_digits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(pi_digits[5])
9

This list contains elements of type bool.

In [13]:
bool_list = [False, True, True, False, True]
print(bool_list[3])
False

It is even possible for a single list to contains elements of several different data types.

In [14]:
varied_list = [False, "one", 2, 3.0]
print(type(varied_list))
print(type(varied_list[0]))
print(type(varied_list[1]))
print(type(varied_list[2]))
print(type(varied_list[3]))
<class 'list'>
<class 'bool'>
<class 'str'>
<class 'int'>
<class 'float'>

In fact, it is even possible for lists to contain other lists! We will further discuss this concept soon.

Altering Lists

The elements of a list can be altered after the list has been created. We can make changes to the elements of a list in the following ways:

  1. Updating elements We can replace the value stored at a particular index with any other value.
  2. Adding elements We can insert new elements into a list at any position that we choose.
  3. Removing elements We can delete any element from a list.

We illustrated each of these concepts below.

In [15]:
# Define the list Fruit.
Fruit = ['apple', 'ornge', 'lemon', 'grap', 'peach']
print(Fruit)
['apple', 'ornge', 'lemon', 'grap', 'peach']

Modifying elements of a list

Two of the elements in our list were misspelled. We will replace these elements with correctly spelled entries.

In [16]:
Fruit[1] = 'orange'
Fruit[3] = 'grape'
print(Fruit)
['apple', 'orange', 'lemon', 'grape', 'peach']

Inserting elements into a list

The insert() list method allows us to add elements to a list at a specified position. Any elements whose previous indices were greater than or equal to the index of the newly inserted element will be pushed back one position.

In [17]:
# Insert plum as the second element of the list.
Fruit.insert(1, 'plum')
print(Fruit)
['apple', 'plum', 'orange', 'lemon', 'grape', 'peach']
In [18]:
# Insert lime as the fifth element of the list.
Fruit.insert(4, 'lime')
print(Fruit)
['apple', 'plum', 'orange', 'lemon', 'lime', 'grape', 'peach']

Appending elements to a list

The append() method is similar to insert(), except that no position is specified. Appended elements are always added to the end of the list.

In [19]:
# Add strawberry and raspberry to the end of the Fruit list.
Fruit.append('strawberry')
Fruit.append('raspberry')
print(Fruit)
['apple', 'plum', 'orange', 'lemon', 'lime', 'grape', 'peach', 'strawberry', 'raspberry']

Deleting list elements by index

We may use the del keyword to delete the element of a list at a certain index.

In [20]:
# Delete the third element of the Fruit list.
del Fruit[2]
print(Fruit)
['apple', 'plum', 'lemon', 'lime', 'grape', 'peach', 'strawberry', 'raspberry']

Keep in mind that once an element is deleted (or inserted), all later elements will have their indices updated.

In [21]:
# Delete the first two elements of the Fruit list.
del Fruit[0]
del Fruit[0]
print(Fruit)
['lemon', 'lime', 'grape', 'peach', 'strawberry', 'raspberry']

Deleting list elements by value

The remove() method will search through a list and remove the first element that matches the supplied argument. If there are multiple elements equal to the given argument, only the one with the lowest index will be deleted.

In [22]:
# Remove the first instance of peach from the list.
Fruit.remove('peach')
print(Fruit)
['lemon', 'lime', 'grape', 'strawberry', 'raspberry']
In [23]:
# Add a second lime element to the end of the list.
Fruit.append('lime')
print(Fruit)
['lemon', 'lime', 'grape', 'strawberry', 'raspberry', 'lime']
In [24]:
# Remove the first instance of lime from the list. 
Fruit.remove('lime')
print(Fruit)
['lemon', 'grape', 'strawberry', 'raspberry', 'lime']

Example: Altering Lists

A list of integers is defined in the next cell. Perform the requested tasks on this list.

In [25]:
intList = [3, 11, 45, 14, 47, 18, 42, 41, 20, 13, 33, 6]

Update the element whose value is 18 to have a value of 28. Print intList.

In [26]:
intList[5] = 28
print(intList)
[3, 11, 45, 14, 47, 28, 42, 41, 20, 13, 33, 6]

Insert an element with a value of 42 between the elements whose values are 20 and 13. Print intList.

In [27]:
intList.insert(9, 42)
print(intList)
[3, 11, 45, 14, 47, 28, 42, 41, 20, 42, 13, 33, 6]

Use the append() method to add an element with a value of 34 to the end of the list. Print intList.

In [28]:
intList.append(34)
print(intList)
[3, 11, 45, 14, 47, 28, 42, 41, 20, 42, 13, 33, 6, 34]

Use the remove() method to delete the first occurence of 42 in the list. Print intList.

In [29]:
intList.remove(42)
print(intList)
[3, 11, 45, 14, 47, 28, 41, 20, 42, 13, 33, 6, 34]

Use the del keyword to delete the first three elements of intList. Print intList.

In [30]:
del intList[0]
del intList[0]
del intList[0]
print(intList)
[14, 47, 28, 41, 20, 42, 13, 33, 6, 34]

The output of the last cell should be: [14, 47, 28, 41, 20, 42, 13, 33, 6, 34]

Tuples

In addition to lists, Python provides another data type that can be used to store sequences of values. This second data type is called a tuple. In many ways, lists and tuples behave very similarly. Elements of a tuple each have an index, and are accessed in the same way as in a list. The fundamental distinction between the two data types is that tuples are immutable, meaning that once a tuple is created, it's contents cannot be altered.

Syntactically, a tuple is define much in the same way as a list, except that parentheses () are used to define a tuple in place of the square brackets [] that are used for a list.

In the cell below, we define a tuple containing integer values.

In [31]:
my_tuple = (159, 348, 214, 381, 194)

We can access elements of a tuple in the same way as we would elements of a list.

In [32]:
print(my_tuple[0])
print(my_tuple[2])
print(my_tuple[-2])
159
214
381

Because of the immutability of tuples, we will get an error if we attempt to change the contents of an already created tuple.

In [33]:
my_tuple[1] = 999
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-7660b016544b> in <module>
----> 1 my_tuple[1] = 999

TypeError: 'tuple' object does not support item assignment

Although you cannot edit the contents of a tuple, you may reassign a new value to a variable that had contains a tuple. This is illustrated in the cell below.

In [34]:
my_tuple = 7
print(my_tuple)
7