Code
# Define list variables
= [4, 23, 654, 2, 0, -12, 4391]
num_list = ['energy', 'water', 'carbon'] str_list
โฌ ๏ธ Previous Session | ๐ Course Home | ๐ฆ EDS217 Vibes | โก๏ธ Next Session |
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.
Session 1.2 Topics
len()
, min()
, max()
We will work through this notebook together. To run a cell, click on the cell and press โShiftโ + โEnterโ or click the โRunโ button in the toolbar at the top.
๐ This symbol designates an important note about Python structure, syntax, or another quirk.
โถ๏ธ This symbol designates a cell with code to be run.
โ๏ธ This symbol designates a partially coded cell with an example.
A list is a Python object used to contain multiple values. Lists are ordered and changeable. They are defined as follows:
= [4, 23, 654, 2, 0, -12, 4391]
num_list = ['energy', 'water', 'carbon'] str_list
โถ๏ธ <b> Run the cell below. </b>
# Define list variables
= [4, 23, 654, 2, 0, -12, 4391]
num_list = ['energy', 'water', 'carbon'] str_list
While you can create lists containing mixed data types, this is not usually recommended.
The len()
command returns the length of the list.
len(str_list)
>>> 3
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.
min(str_list)
>>> 'carbon'
max(str_list)
>>> 'water'
โ๏ธ <b> Try it. </b>
Use the <code>len()</code>, <code>min()</code>, and <code>max()</code> commands to find the length, minimum, and maximum of <code>num_list</code>.
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 []
.
๐ <b>Note.</b> 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.
2]
num_list[>>> 654
You can also access an element based on its position from the end of the list.
-2]
num_list[>>> -12
โ๏ธ <b> Try it. </b>
Find the 2nd element in <code>str_list</code> 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 :
.
๐ <b>Note.</b> The endpoint index in the slice is <i>exclusive</i>. To slice to the end of the list, omit an endpoint.
2:6]
num_list[>>> [654, 2, 0, -12]
0:4]
num_list[>>> [4, 23, 654, 2]
4]
num_list[:>>> [4, 23, 654, 2]
-6:-1]
num_list[>>> [23, 654, 2, 0,-12]
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.
0:4:2]
num_list[>>> [4, 654]
2]
num_list[::>>>[4, 654, 0, 4391]
A step of -1 returns the list in reverse.
-1]
num_list[::>>> [4391, -12, 0, 2, 654, 23, 4]
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.
= 'antidisestablishmentarianism'
word_str
14]
word_str[>>> 's'
3]
word_str[::>>> 'aistlhnrnm'
Elements can be added to a list using the command list.append()
.
โถ๏ธ <b> Run the cell below. </b>
= ['red', 'blue', 'green', 'black', 'white'] colors
You can add an element to a list in a specific position using the command list.insert()
.
4, 'purple')
colors.insert(print(colors)
>>> ['red', 'blue', 'green', 'black', 'purple', 'white', 'pink']
โ๏ธ <b> Try it. </b>
Add <code>'purple'</code> to the list <code>colors</code> between <code>'green'</code> and <code>'black'</code>.
There are multiple ways to remove elements from a list. The commands list.pop()
and del
remove elements based on indices.
# removes the last element
colors.pop() 2) # removes the third element
colors.pop(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.
'red')
colors.remove(print(colors)
>>> ['blue', 'green', 'black', 'purple', 'white', 'pink']
โ๏ธ <b> Try it. </b>
Remove <code>'pink'</code> and <code>'purple'</code> from <code>colors</code>, using <code>del</code> for one of the strings and <code>list.remove()</code> for the other.
You can sort the elements in a list (numerically or alphabetically) in two ways. The first uses the command list.sort()
.
โถ๏ธ <b> Run the cell below. </b>
= [5.1 , 3.42 , 3.333 , 100.4 , 0.5 , 26.0 , 7.44 , 5.8 , 39.0]
rand_list
rand_list.sort()print(rand_list)
Setting reverse=True
within this command sorts the list in reverse order:
= [5.1 , 3.42 , 3.333 , 100.4 , 0.5 , 26.0 , 7.44 , 5.8 , 39.0]
rand_list =True)
rand_list.sort(reverseprint(rand_list)
>>> [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.
โ๏ธ <b> Try it. </b>
Verify that <code>rand_list</code> was, in fact, sorted in place by using the <code>min()</code> and <code>max()</code> functions to determine the minmum and maximum values in the list and printing the first and last values in the list.
# Print the min and max values in rand_list.
# Print the first and last values in rand_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 , 3.42 , 3.333 , 100.4 , 0.5 , 26.0 , 7.44 , 5.8 , 39.0]
rand_list = sorted(rand_list)
sorted_list print(rand_list[0])
print(sorted_list[0])
>>> 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. A view of a list can be created as follows:
= ['energy', 'water', 'carbon']
str_list = str_list str_list_view
Any in-place operation performed on str_list_view
will also be applied to str_list
. To avoid this, create a copy of str_list
using any of the following methods:
= str_list.copy()
str_list_copy # or
= str_list[:]
str_list_copy # or
= list(str_list) str_list_copy
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.
= ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
rainbow = ['coral', 'chartreuse', 'cyan', 'navy']
shades print( rainbow + shades )
>>> ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'coral', 'chartreuse', 'cyan', 'navy']
Single lists can be repeated by multiplying by an integer.
โถ๏ธ <b> Run the cell below. </b>
= str_list * 2
str_list2 = num_list * 4
num_list4 print( str_list2 )
print( num_list4 )
Sequential lists are valuable tools, particularly for iteration, which we will explore in the next session. The range()
function is used to create an iterable object based on the size of an integer argument.
range(4)
>>> range(0, 4)
To construct a sequential list from the range()
object, use the list()
function.
list(range(4))
>>> [0, 1, 2, 3]
Using multiple integer arguments, the range()
function can be used to generate sequential lists between two bounds: range(start, stop [, step])
.
๐ <b>Note.</b>
Like indexing, all Python functions using <span style="font-style: italic"> start </span> and <span style="font-style: italic"> stop </span> arguments, the <span style="font-style: italic"> stop </span> value is <span style="font-weight: bold"> exclusive </span>.
= list(range(1,11))
range_10 = list(range(1,11,2))
odds_10 print(range_10)
print(odds_10)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1, 3, 5, 7, 9] [