Lists

How can we store information together?

KEY TERMS

  • Lists: a way to store and organize information by putting different values in the same group.

  • Element(s): value(s) or item(s) in a list.

  • Square brackets: [ ], tool used to create a new list, access part of a list, or slice an existing list.

  • Index: label of each element in a list.

  • Zero indexed: the first index in the list is 0.

  • Sublist: a list made from part of a longer list.

  • List slicing: using square brackets to create a sublist of a specified size.

  • Exclusive: the value is not included.

  • Inclusive: the value is included.

When some people go to the grocery store, they make a list of what they want to buy. In that case, the list is a way to keep things organized and store information. In Python, lists serve the same purpose. A list is a sequence of elements, which groups information together. Elements are the values inside of a list. In Python, lists are created by surrounding the elements separated by commas with square brackets [...]. You can put anything in a list, whether it's an integer, string, boolean, or even another list! There can be more than one data type in a list. For example, we can make a list of integers and floats:

>>> [1, 2.0, 3, 4.0]

Or we can make a list of strings:

>>> ['data', 'science', 'is', 'cool']

We can even make lists of lists!

>>> [0.0, False, 1, True, ['data', 'science']]

How many elements are in the list below? How are the elements separated?

>>> [1.0, True, 200, ['data', 'science']]

What is the data type of each element in this list?

Creating and Accessing a List

To create a new list, we enclose a set of comma-separated elements with square brackets, as shown below. Each element has an index, which is the position of the element in the list. Lists in Python are zero indexed, which means that when we reference items in the list, we consider the first element to be at index 0, the second element at index 1, and so on.

To save a list, you have to assign it to a name. Once you assign it to a name, you can reference the name to access the list. If you do not give the list a name, you will not be able to use it later.

# we use square brackets to create a list
# this creates an empty list
>>> l = []

# let's make a list with elements in it
>>> letters = ['l', 'e', 't', 't', 'e', 'r', 's']
#   element:    1    2    3    4    5    6    7
#   index:      0    1    2    3    4    5    6

To access a single element in a list, we use the square brackets containing the index of the element we want.

# the first element of the list is at index 0
# this will return 'l'
>>> letters[0]
'l'

# the second element of the list is at index 1
# this will return 'e'
>>> letters[1]
'e'

What is the index of the last element in letters? How does it relate to the length of the list?

Checking Elements (in / not in)

If we want to check whether a value is in our list, then we can use the operator in. The operator returns True if the value is in the list and False if the value is not in the list. The format is <value> in <list name>.

>>> numbers = [1, 2, 3, 4]

>>> 1 in numbers
True

>>> "hi" in numbers
False

We can also use not to get the opposite effect. If we say not in , then it will return True if the value is NOT in the list and False if the value is in the list.

>>> numbers = [1, 2, 3, 4]

>>> "hello" not in numbers
True

>>> 2 not in numbers
False

This is a useful tool when there is a long list, and you are not sure whether a certain value is in the list.

Updating Items

Not only is it possible to check whether elements are in a list, but it is also possible to update or change values in a list. Say the third value in a list was misspelled, then you could update the value in the list to the correct value. To do this, assign the element at the specified index to the updated value which looks like this: <list name>[<index>] = <updated value>

Let's look at some examples!

>>> nature = ["leaf", "tree", "pla", "grass"] # Misspelled plant!

>>> nature[2] # The element we want to change is at index 2!
"pla"

>>> nature[2] = "plant" # UPDATING HAPPENS HERE

>>> nature # Now we can see the changes
["leaf", "tree", "plant", "grass"]

Being able to update elements in a list is useful for changing one part of the list. Instead of creating a whole new list, you can just change certain elements.

List Slicing

To access more than one element at a time, we will use list slicing. List slicing is where you cut out a section from a list to make a smaller list. The elements accessed will stay in the order of the original list. When we do list slicing, it creates a new list that is a subset of the original list.

List slicing is similar to accessing a single element in the list, except we use the format [<start> : <end>] to get a list of the elements from the start index until the end index (note that the end index is exclusive, so we include all the elements up until the end index, but not the end index itself). The new list that is made is called a sublist, which means that it is a list that holds part of the elements from the original list.

>>> letters = ['l', 'e', 't', 't', 'e', 'r', 's']
#   element:    1    2    3    4    5    6    7
#   index:      0    1    2    3    4    5    6

# slice the list
# this returns a list of indexes 0 to 3 of letters, excluding index 3
>>> letters[0:3]
['l', 'e', 't']

If we don't provide a start index or end index while slicing a list, Python considers the default start index to be 0 and the default end index to be the length of the list.

# if you don't provide a start index, Python defaults to 0
>>> letters[:4]
['l', 'e', 't', 't']

# if you don't provide an end index, Python defaults to the length of the list
# in this case, the length of the list is 7
>>> letters[4:]
['e', 'r', 's']

# if you don't provide either
# Python defaults to 0 for the start, and the length of the list for the end
# this creates a list of all the elements in the original list
>>> letters[:]
['l', 'e', 't', 't', 'e', 'r', 's']
q4 = [2018, ['data', 'science', 'is', 'cool'], True]

Using the list above, what would q4[1][:2] return?

Hint: Make sure to read the code from left to right. Think about what q4[1] would return.

Adding Items

Now that we know how to create and access elements in a list, let's look at how we can add or remove these elements.

To add a single element to a list, we can use the list method .append(). This method takes in a new element and adds it to the end of the original list.

# this is a list of states on the West Coast of the US
>>> west_coast = ['Washington', 'Oregon']

# looking at the US map, we see this list is missing California! 
# we can add it using .append()
>>> west_coast.append('California')
>>> west_coast
['Washington', 'Oregon', 'California']

But what if we want to add multiple items to a list? Using .append(), we would have to add each item individually! Instead, we can use the list method .extend() to add a list of elements to the end of another list.

# west_coast only includes states in the continental US
# but now we want to add Alaska and Hawaii to our list
# these states (including Alaska and Hawaii) are known as the Pacific States
>>> west_coast
['Washington', 'Oregon', 'California']

>>> west_coast.extend(['Alaska', 'Hawaii'])
>>> west_coast
['Washington', 'Oregon', 'California', 'Alaska', 'Hawaii']

What is the difference between .append() and .extend()? What do you pass in to each function?

After adding Alaska and Hawaii, the list west_coast should contain 5 elements. To verify the length of a list, we can use the function len(). This returns the number of elements in a list.

# to find the length of the list west_coast, call len() on west_coast
>>> len(west_coast)
5

Deleting Items

Now, suppose we've changed our minds - we don't want to include Alaska and Hawaii in our list of West Coast states after all! We can use the format del <list name>[<index>] to remove the single element at the specified index in the list. This means we'll need to know the index of the element we want to remove.

# let's remove 'Alaska' and 'Hawaii' from west_coast
>>> west_coast 
['Washington', 'Oregon', 'California', 'Alaska', 'Hawaii']

# 'Alaska' is at index 3
>>> del west_coast[3]
>>> west_coast
['Washington', 'Oregon', 'California', 'Hawaii']

# notice that 'Hawaii' was originally at index 4, but now it's at index 3 
# why? because we've modified the list by removing 'Alaska'!
>>> del west_coast[3]
>>> west_coast
['Washington', 'Oregon', 'California']

# after removing 2 items, west_coast is 3 items long
>>> len(west_coast)
3

Remember that .append(), .extend(), and del all modify the original list!

It is possible to delete multiple items from a list if they are next to each other in the original list. To delete multiple elements in the list you will use the format: del <sublist>. The sublist is a list of the elements you want deleted. One way to make a sublist is to use list slicing. A way to think about this is that you are using list slicing to identify the part of the list you do not want, and then telling Python you want to delete it.

>>> west_coast
['Washington', 'Oregon', 'California']

>>> west_coast[1:] # Identify sublist we want to delete.
['Oregon', 'California']

>>> del west_coast[1:] # Deleting that part from the original list.
>>> west_coast # Original list is updated.
['Washington']

Summary

Lists

  • Lists contain sequences of elements with multiple different data types.

  • Lists are created using square brackets containing comma-separated values and are zero indexed.

  • Use in / not in to see if a value exists within a list.

  • Update a value in the list by reassigning the indexed value with the updated value.

  • Access an element in a list using square brackets containing the index of the element. To access multiple elements, we can use list slicing.

  • Use .append() to add an item to a list. Use .extend() to add multiple items to a list.

  • The length of a list can be found using the function len().

  • Use del to remove an element at a specified index from a list.

Last updated