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
.
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
.
type(planets)
We can also print lists.
print(planets)
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]
.
# Print the 1st element of planets
print(planets[0])
# Print the 3rd element of planets
print(planets[2])
# Print the 8th element of planets
print(planets[7])
We will get an error if we try to access a list element that does not exist.
print(planets[8])
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.
# Print the last element of planets.
print(planets[-1])
# Print the 3rd from last element of planets.
print(planets[-3])
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.
print(planets[3])
print(planets[-5])
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
.
print(type(planets))
print(type(planets[4]))
It is possible to create lists that contain other data types. The following list contains elements of type int
.
pi_digits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(pi_digits[5])
This list contains elements of type bool
.
bool_list = [False, True, True, False, True]
print(bool_list[3])
It is even possible for a single list to contains elements of several different data types.
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]))
In fact, it is even possible for lists to contain other lists! We will further discuss this concept soon.
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:
We illustrated each of these concepts below.
# Define the list Fruit.
Fruit = ['apple', 'ornge', 'lemon', 'grap', 'peach']
print(Fruit)
Two of the elements in our list were misspelled. We will replace these elements with correctly spelled entries.
Fruit[1] = 'orange'
Fruit[3] = 'grape'
print(Fruit)
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.
# Insert plum as the second element of the list.
Fruit.insert(1, 'plum')
print(Fruit)
# Insert lime as the fifth element of the list.
Fruit.insert(4, 'lime')
print(Fruit)
The append()
method is similar to insert()
, except that no position is specified. Appended elements are always added to the end of the list.
# Add strawberry and raspberry to the end of the Fruit list.
Fruit.append('strawberry')
Fruit.append('raspberry')
print(Fruit)
We may use the del
keyword to delete the element of a list at a certain index.
# Delete the third element of the Fruit list.
del Fruit[2]
print(Fruit)
Keep in mind that once an element is deleted (or inserted), all later elements will have their indices updated.
# Delete the first two elements of the Fruit list.
del Fruit[0]
del Fruit[0]
print(Fruit)
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.
# Remove the first instance of peach from the list.
Fruit.remove('peach')
print(Fruit)
# Add a second lime element to the end of the list.
Fruit.append('lime')
print(Fruit)
# Remove the first instance of lime from the list.
Fruit.remove('lime')
print(Fruit)
A list of integers is defined in the next cell. Perform the requested tasks on this list.
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
.
intList[5] = 28
print(intList)
Insert an element with a value of 42 between the elements whose values are 20 and 13. Print intList
.
intList.insert(9, 42)
print(intList)
Use the append()
method to add an element with a value of 34 to the end of the list. Print intList
.
intList.append(34)
print(intList)
Use the remove()
method to delete the first occurence of 42 in the list. Print intList
.
intList.remove(42)
print(intList)
Use the del
keyword to delete the first three elements of intList
. Print intList
.
del intList[0]
del intList[0]
del intList[0]
print(intList)
The output of the last cell should be: [14, 47, 28, 41, 20, 42, 13, 33, 6, 34]
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.
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.
print(my_tuple[0])
print(my_tuple[2])
print(my_tuple[-2])
Because of the immutability of tuples, we will get an error if we attempt to change the contents of an already created tuple.
my_tuple[1] = 999
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.
my_tuple = 7
print(my_tuple)