End interactive session 2A
Code
# Define list variables
= [4, 23, 654, 2, 0, -12, 4391]
num_list = ['energy', 'water', 'carbon'] str_list
π Getting to know lists
Python has four collection data types, the most common of which is the list. This session introduces lists and a few of the important list operations. We will also cover indexing, a key feature of programming.
Before we begin our interactive session, please follow these steps to set up your Jupyter Notebook:
+
button in the top left cornerPython 3.10.0
from the Notebook optionsUntitled.ipynb
tabSession_2A_Lists.ipynb
# Day 2: Session A - Lists
[Link to session webpage](https://eds-217-essential-python.github.io/course-materials/interactive-sessions/2a_lists.html)
Date: 09/04/2024
Remember to save your work frequently by clicking the save icon or using the keyboard shortcut (Ctrl+S or Cmd+S).
Letβs begin our interactive session!
len()
, min()
, max()
π This symbol designates an important note about Python structure, syntax, or another quirk.
βοΈ This symbol designates code you should add to your notebook and run.
A list is a Python object used to contain multiple values. Lists are ordered and changeable. They are defined as follows:
βοΈ Try it. Add the cell below to your notebook and run it.
While you can create lists containing mixed data types, this is not usually recommended.
The len()
command returns the length of the list.
The min()
and max()
commands are used to find the minimum and maximum values in a list. For a list of strings, this corresponds to the alphabetically first and last elements.
βοΈ Try it. Use the len()
, min()
, and max()
commands to find the length, minimum, and maximum of num_list
.
The index is used to reference a value in an iterable object by its position. To access an element in a list by its index, use square brackets []
.
π Python is zero-indexed. This means that the first element in the list is 0, the second is 1, and so on. The last element in a list with \(n\) elements is \(n - 1\).
You can also access an element based on its position from the end of the list.
βοΈ Try it. Find the 2nd element in str_list
in two different ways. Remember that Python is zero-indexed!
Accessing a range of values in a list is called slicing. A slice specifies a start and an endpoint, generating a new list based on the indices. The indices are separated by a :
.
π The endpoint index in the slice is exclusive. To slice to the end of the list, omit an endpoint.
This code returns the 2nd and 3rd elements of the num_list
This code would return everything from the 4th element to the end of the list:
βοΈ Try it. Before running each of the following commands in a new cell in your notebook, try to determine what output you expect
Although less common, it is also possible to specify a step size, i.e. [start:stop:step]
. A step size of 1 would select every element, 2 would select every other element, etcβ¦
A step of -1 returns the list in reverse.
Like lists, strings can also be indexed using the same notation. This can be useful for many applications, such as selecting files in a certain folder for import based on their names or extension.
βοΈ Try it. Add the cell below to your notebook and run it.
Elements can be added to a list using the command list.append()
.
βοΈ Try it. Add the cell below to your notebook and run it.
You can add an element to a list in a specific position using the command list.insert(i, x)
where i
is the position where the element x
should be added.
βοΈ Try it. Add βpurpleβ
to the list colors
between βgreenβ
and βblackβ
.
There are multiple ways to remove elements from a list. The commands list.pop()
and del
remove elements based on indices.
colors.pop() # removes the last element
colors.pop(2) # removes the third element
del colors[2] # removes the third element
del colors[2:4] # removes the third and fourth elements
The command list.remove()
removes an element based on its value.
βοΈ Try it. Remove pink
and purple
from colors
, using del
for one of the strings and list.remove()
for the other.
You can sort the elements in a list (numerically or alphabetically) in two ways. The first uses the command list.sort()
.
βοΈ Try it. Add the cell below to your notebook and run it.
[0.5, 3.333, 3.42, 5.1, 5.8, 7.44, 26.0, 39.0, 100.4]
Setting reverse=True
within this command sorts the list in reverse order:
βοΈ Try it. Add the cell below to your notebook and run it.
[100.4, 39.0, 26.0, 7.44, 5.8, 5.1, 3.42, 3.333, 0.5]
So far, all of the list commands weβve used have been in-place operators. This means that they perform the operation to the variable in place without requiring a new variable to be assigned. By contrast, standard operators do not change the original list variable. A new variable must be set in order to retain the operation.
βοΈ Try it. Verify that rand_list
was, in fact, sorted in place by using the min()
and max()
functions to determine the minmum and maximum values in the list and printing the first and last values in the list.
The other method of sorting a list is to use the sorted()
command, which does not change the original list. Instead, the sorted list must be assigned to a new variable.
5.1
0.5
To avoid changing the original variable when using an in-place operator, it is wise to create a copy. There are multiple ways to create copies of lists, but it is important to know the difference between a true copy and a view.
The difference between a copy
and a view
is a critical topic in Python and something we will come back to later in the class when working with DataFrames. Python only makes a copy of data when it is necessary, so make sure you understand the difference!
A view of a list can be created as follows:
Any in-place operation performed on str_list_view
will also be applied to str_list
. For example, look what happens when you run this code:
βοΈ Try it. Add the cell below to your notebook and run it.
['carbon', 'energy', 'water']
str_list_view
was just a βviewβ into to the str_list
variable, but a copy!
To avoid this, create a copy of str_list
using any of the following methods:
In addition to adding single elements to a list using list.append()
or list.insert()
, multiple elements can be added to a list at the same time by adding multiple lists together.
βοΈ Try it. Add the cell below to your notebook and run it.
['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'coral', 'chartreuse', 'cyan', 'navy']
Single lists can be repeated by multiplying by an integer.
βοΈ Try it. Add the cell below to your notebook and run it.
Sequential lists are valuable tools, particularly for iteration, which we will explore in later sessions. The range()
function is used to create an iterable object based on the size of an integer argument.
To construct a sequential list from the range()
object, use the list()
function.
Using multiple integer arguments, the range()
function can be used to generate sequential lists between two bounds: range(start, stop [, step])
.
π Like indexing, all Python functions using start and stop arguments, the stop value is exclusive .
βοΈ Try it. Add the cell below to your notebook and run it.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
End interactive session 2A