Lesson 3d - Containers
Suppose we had to keep track of the class average. We can’t just make a variable for each mark because there could be dozens, maybe hundreds, of marks to store. This is where containers come in.
Containers can hold an arbitrary amount of data. There are different kinds of containers, and we’ll be going over four of them today. Lists, tuples, sets, and dictionaries.
Table of Contents
Lesson Objectives
- Use containers to store data.
- Learn the differences between lists, tuples, sets, and dictionaries.
- Use the
help()
function to discover more functions.
Lists
Lists are the most common type of container because of their ease of use.
They can hold any number of objects, which can also change throughout the program. This means that we can add and remove data from the list after its initial declaration.
The contents of a list are also ordered.
In the context of containers, for a container to be ordered, there’s always a “first” element, followed by a “next” element.
It does not mean that it sorts the data.
Lists are created by surrounding data with square brackets [ ]. The line of code below creates a list with some pieces of data.
myList = [1, 2.0, 3, "hello", 2]
Length of a List
You’ll notice in the next few sections that lists behave a lot like strings in a lot of scenarios. Just like with strings, you can find the number of items a list contains by using the len()
function.
Input
myList = [1, 2.0, 3, "hello", 2]
print(len(myList))
Output
5
List Indexing
You can also access a particular index of a list using the square bracket notation we use when working with strings.
Input
myList = [1, 2.0, 3, "hello", 2]
print(myList[2])
Output
3
Just like with strings, Python will give you an error if you try to access a list index that does not exist. Using myList = [1, 2.0, 3, "hello", 2]
as an example, accessing the 8th index by doing myList[8]
will give you an error because the 8th index does not exist.
List Slicing
Once again, just like strings, we can also slice portions of lists.
Input
myList = [1, 2.0, 3, "hello", 2]
print(myList[1:3])
Output
[2.0, 3]
Multidimensional Lists
Lists can also contain other lists!
myList = [ [1, 2, 3], ["a", "b", "c"] ]
To access the integer 3
from the first list inside the list, we have to do the following.
myList[0][2]
myList[0]
will give us [1, 2, 3]
. Since we want the 3
, we need to index again, adding another [2]
to it. This leaves us with myList[0][2]
.
Dot Notation for Functions
Unlike all of the functions we’ve used before, the following couple functions have a different syntax. You’ll see that it follows the following format:
variable.function()
Functions that follow the dot notation above are unique to that particular data type. In this case, append()
will only work on lists.
To get a full list of dot notation functions for any variable and data type, use the help()
function.
A lot of functions will begin with underscores _. Skip through those ones, they are meant mostly for Python’s use rather than your own.
Input
myList = [1, 2, 3, 4]
help(myList)
Output
Help on list object:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
...
Output is too large to put here, try it out in your Python interpreter!
Adding Elements to a List
The easiest way to add an element to a list is to use the append()
function. The append()
function adds an element to the end of the list.
Input
myList = [1, 2.0, 3, "hello", 2]
myList.append(24)
print(myList)
Output
[1, 2.0, 3, "hello", 2, 24]
Alternatively, you can use the insert()
function if you’d like to insert an element at a specific index.
Input
myList = [1, 2.0, 3, "hello", 2]
myList.insert(3, 24) # Insert the value 24 into index 3
print(myList)
Output
[1, 2.0, 3, 24, "hello", 2]
Combining Lists
To combine lists, you can use the extend()
function.
Input
myList = [1, 2, 3, 4]
myList2 = [5, 6, 7, 8]
myList.extend(myList2)
print(myList)
Output
[1, 2, 3, 4, 5, 6, 7, 8]
Append vs Extend
Append and extend are often mixed up.
- Append
- Adds an element to the end of a list.
- Extend
- Combines two lists.
The code below incorrectly uses append to try and combine 2 lists.
Input
myList = [1, 2, 3, 4]
myList2 = [5, 6, 7, 8]
myList.append(myList2)
print(myList)
Output
[1, 2, 3, 4, [5, 6, 7, 8]]
As you can see, rather than combining the 2 lists, it ends up making myList2
an item in myList
.
Removing Elements from a List
To remove the last element in a list, you can use the pop()
function.
Input
myList = [1, 2.0, 3, "hello", 2]
myList.pop()
print(myList)
Output
[1, 2.0, 3, "hello"]
pop()
also returns the value that was removed.Input
myList = [1, 2.0, 3, "hello", 2] removedElement = myList.pop() print(myList) print(f"The removed value was {removedElement}")
Output
[1, 2.0, 3, "hello"] The removed value was 2
If you want to remove a specific index, you can use the pop()
function again, but specify which index to remove.
Input
myList = [1, 2.0, 3, "hello", 2]
myList.pop(3)
print(myList)
Output
[1, 2.0, 3, 2]
If you’d rather remove a specific element from a list (a value rather than an index), you can use the remove()
function.
Input
myList = [1, 2.0, 3, "hello", 2]
myList.remove(3)
print(myList)
Output
[1, 2.0, "hello", 2]
The remove()
function will only remove the first occurrence of a value.
List Concatenation and Repetition
Just like strings, we can concatenate and repeat lists.
Concatenation
Input
myList = [1, 2.0, 3, "hello", 2]
myList2 = [5, 2, 1]
print(myList + myList2)
Output
[1, 2.0, "hello", 2, 5, 2, 1]
Repetition
Input
myList = [1, 2]
print(myList * 3)
Output
[1, 2, 1, 2, 1, 2]
Other Useful List Functions
If you want to find what the index of a particular value, you can use the index()
function.
Input
myList = [1, 2.0, 3, "hello", 2]
print(myList.index(3))
Output
2
Just like the remove()
function, index()
will only find the first occurrence of a value.
If you want to find the amount of times a particular value appears in a list, you can use the count()
function.
Input
myList = [1, 2.0, 3, "hello", 2]
print(myList.count(2))
Output
2
In this case, it considers 2.0 and 2 to have the same value.
If you want to sort the contents of a list, you can use the sort()
function.
Input
myList = [53, 23, 12, -2, 43.2, 43]
myList.sort()
print(myList)
Output
[-2, 12, 23, 43, 43.2, 53]
And finally, if you want to reverse the contents of a list, you can use the reverse()
function.
Input
myList = [53, 23, 12, -2, 43.2, 43]
myList.reverse()
print(myList)
Output
[43, 43.2, -2, 12, 23, 53]
Tuples
Tuples are similar to lists in a lot of ways. Tuples are also containers that store ordered data, and they index and slice the exact same way as lists.
What makes tuples unique is that, once they’re created, they can’t be modified. This means that you can’t add or remove new elements from a tuple. To do so would mean creating a duplicate tuple with the new changes.
Tuples are less commonly used because of this trait, but it does speed up some computational processes.
To create a tuple, you use round brackets ( ) rather than square brackets [ ].
myTuple = (1, 2, 3, 4)
If a tuple contains only one object, you need to include a comma inside the brackets. If you don’t, Python will see the brackets as indicating the order of operations.
myTuple = (1,)
Lists vs Tuples
Take the time to use the help()
function on a list and tuple to compare the available functions for the two data types.
- Functions for lists
- append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort
- Functions for tuples
- count, index
Sets
Sets are also similar to lists in a few ways. They are also containers that store data, and this container can be modified (meaning you can add and remove elements). Sets, however, are not ordered and they do not allow for duplicate elements (much like mathematical sets).
To create a set, you use curly brackets { }.
mySet = {1, 2, 3, 4}
Since sets are unordered, you can’t slice or index them. There isn’t a “first” or “second” element in a set.
The most common use-case for a set is to remove duplicate elements from a list. You can turn a list into a set by using the set()
function, and similarly, you can turn a set into a list using the list()
function.
Input
myList = [1, 2, 5, 2, 2, 4, 2, 4, 6, 4]
mySet = set(myList)
print(mySet)
Output
{1, 2, 4, 5, 6}
Dictionaries
Dictionaries are the most distinct of all the containers. They consist of “key-value pairs”. Rather than using index numbers to index values in the list, dictionaries use “keys” for indexing.
They work very similarly to dictionaries in real life. The key would be the word, whereas the value would be the definition. To find the definition of a word, you need to search the dictionary for its key (the word itself). See the code below for an example.
Input
myDict = {"x": 1, "y": 3, "z": -2}
print(myDict["x"])
print(myDict["z"])
Output
1
-2
Dictionaries are defined similarly to sets, using curly braces { }. However, because they consist of key-value pairs, the curly braces contain <key>: <value>
“objects”. After the dictionary is created, you can access any of the values by referencing its key. We defined “x” to have a value of 1, so when we index “x” in the print statements later on, we get back 1.
Just like sets, dictionaries cannot contain duplicate keys (they can however contain duplicate values.)
Key Points / Summary
- Containers store multiple “cells” of data.
- Lists, tuples, sets, and dictionaries are all containers.
- You can use the
help()
function to list out all functions unique to a particular data type.