Lesson 04 - Introduction to Lists

The following topics are discussed in this notebook:

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

Additional Resources

A list is a tool for storing sets of values. Individul values within a list are assigned a type of address called an index. The index of a value in a list provides us with a means of accessing that particular value.

Defining Lists

When defining a list in Python, we write the elements of the list between a pair of square braces, separated by commas.

In [1]:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
In [2]:
type(planets)
Out[2]:
list
In [3]:
print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Accessing elements in a list

An individual value in a list is called an element of the list. Elements in a list are assigned an order when the list is defined, with 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, 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.

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

� Exercise

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

List Element Types

The object planets we defined above has time list. The elements of planets 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 time 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'>

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']

� Exercise

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]