There are several functions that can take lists as arguments. We will present five such functions here.
len()
returns the number of items in the list. sum()
returns the sum of the elements in a list. This only works on numerical lists.max()
returns the largest item in the list. min()
returns the smallest item in the list. sorted()
returns a sorted copy of the list, but does not change the list itself.We will illustrate the use of these functions using the two lists below.
# Starting lineup in a recent Cardinals game, along with jersey numbers.
cardinals = ['Carpenter', 'Pham', 'DeJong', 'Fowler', 'Molina', 'Martinez', 'Wong', 'Grichuk', 'Wacha']
jerseys = [13, 28, 11, 25, 4, 58, 16, 15, 52]
# Find the length of the lists.
print(len(cardinals))
print(len(jerseys))
# Sum the jerseys list.
print(sum(jerseys))
# Find min and max of cardinals list.
print(min(cardinals))
print(max(cardinals))
# Find min and max of jersey list.
print(min(jerseys))
print(max(jerseys))
# Print sorted cardinals list, as well as original list.
print(sorted(cardinals))
print(cardinals)
# Print sorted jersey list, as well as original list.
print(sorted(jerseys))
print(jerseys)
We have already seen a few list methods such as insert()
, append()
, and remove()
. Notice that all three of these method actually alters the list that they are called on. One difference between methods and other functions is that methods have the ability to change the object that they are acting on, where as non-method functions generally do not.
There are many list methods in addition to the three that we have seen. We will introduce two more here.
sort()
sorts the elements of a list in ascending order. These changes affect the list itself. reverse()
arranges the elements of the list in reverse order. This affects the list itself.listA = [6, 9, 1, 4, 7, 3, 6, 4, 5, 2]
listA.sort()
print(listA)
listB = [6, 9, 1, 4, 7, 3, 6, 4, 5, 2]
listB.reverse()
print(listB)
� Exercise
Add lines of code to the cell below to sort listC
in descending order. Then print listC
.
listC = [6, 9, 1, 4, 7, 3, 6, 4, 5, 2]
listC.sort()
listC.reverse()
Occasionally, we will need to need to work with a portion of a list, rather than the entire list. Slicing is a method of creating a sublist of consecutive elements drawn from another list.
Assume that myList
is a Python list, and let i
and j
be integers.
myList[i:j]
will generate a sublist of myList
that begins with the element at index i
and contains all elements up to but not including the element at index j
. myList[i:]
will generate a sublist of myList
that begins with the element at index i
and contains all later elements. myList[:j]
will generate a sublist of myList
that contains all elements up to but not including the element at index j
.# Simple Slicing Example
simpleList = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print(simpleList[3:7])
print(simpleList[5:])
print(simpleList[:8])
We can also use negative indices when specifying a slice of a list.
# Print the last 6 elements of simpleList
print(simpleList[-6:])
# Print all but the first two and last two elements of simpleList
print(simpleList[2:-2])
� Exercise
CompCo is an company that manufactures laptop computers. The vector sales
below provides CompCo's total monthly sales for each month of 2016, measured in US dollars. The results are listed in order of month.
sales = [52353, 43724, 32191, 34914, 44671, 37139, 49341, 57139, 55104, 45193, 52167, 61294]
CompCo needs to calculate their quarterly sales for each quarter in 2016.
Define four new variables Q1, Q2, Q3, and Q4 in the next cell.
Use a combination of slicing and the sum()
function.
Q1 = sum(sales[:3])
Q2 = sum(sales[3:6])
Q3 = sum(sales[6:9])
Q4 = sum(sales[9:])
Print the variables Q1, Q2, Q3, and Q4.
print(Q1)
print(Q2)
print(Q3)
print(Q4)
It is possible for the elements of a list to be lists themselves. Let's consider a simple example.
metaList = [ [4, 2], ['a', 'b', 'c', 'd'], [1.1, 2.2, 3.3] ]
Notice that metalist
is a list that contains three elements, each of which is also a list.
metaList[0]
is a list of two int
values, [4, 2]
.metaList[1]
is a list of four str
, ['a', 'b', 'c', 'd']
.metaList[2]
is a list of three float
values, [1.1, 2.2, 3.3]
.We can access elements of the inner lists by using two sets of square braces and two indices.
For example, since metaList[1]
is the list ['a', 'b', 'c', 'd']
, we can access the str
'c'
with metaList[1][2]
.
print(metaList[1][2])
� Exercise
In the cell below, we have created lists for 9 midwest states. Each state list contains the names of the cities in that state with a population of 100,000 or greater.
MO_list = ['Independence', 'Kansas City', 'Springfield', 'St. Louis']
IL_list = ['Aurora', 'Chicago', 'Joliet', 'Napierville', 'Peoria', 'Rockford', 'Springfield']
AR_list = ['Little Rock']
KS_list = ['Kansas City', 'Olathe', 'Overland Park', 'Topeka', 'Wichita']
IA_list = ['Cedar Rapids', 'Des Moines']
NE_list = ['Lincoln', 'Omaha']
OK_list = ['Norman', 'Oklahoma City', 'Tulsa']
TN_list = ['Chattanooga', 'Clarksville', 'Knoxville', 'Memphis', 'Nashville']
KY_list = ['Lexington', 'Louisville']
We will now create a list that contains each of these 9 lists as its elements.
cities_100K = [AR_list, IA_list, IL_list, KS_list, KY_list, MO_list, NE_list, OK_list, TN_list]
Without referring directly to any of the 9 original lists, print out a list of the cities in Kansas with a population of 100,000 or greater.
print(cities_100K[3])
Without referring directly to any of the 9 original lists, print out a list of the cities in Nebraska with a population of 100,000 or greater.
print(cities_100K[6])
Using only the list cities_100K
, print the element 'St. Louis'
.
print(cities_100K[5][3])
Using only the list cities_100K
, print the element 'Joliet'
.
print(cities_100K[2][2])
Assume that var1
is a variables of type int
, float
, str
, or bool
. We have seen before that if we create a new variable var2
and set its initial value to be equal to that of var1
, then var2
will initially contain the same value as var1
, but will be its own distinct variable whose value can be changed independent of var1
. This is illustrated in the following two cells.
var1 = 37
var2 = var1
print(var1)
print(var2)
var2 = "blah"
print(var1)
print(var2)
The situation is different for lists, however. If we have a list called list1
and we set list2
to be equal to list1
, then list1
and list2
will be two different names of the same list. Any changes made to list1
will also effect list2
and vice versa.
list1 = [3, 8, 2]
list2 = list1
print(list1)
print(list2)
list2.append(37)
print(list1)
print(list2)
What if we want to actually create a new, entirely separate, copy of an already existing list? It turns out that Python provides two ways of doing a such.
copy()
method of the list that we wish to duplicate.Let's see first see how to duplicate a list using the copy()
method.
dup1 = list1.copy()
print(list1)
print(dup1)
dup1.append(42)
print(list1)
print(dup1)
We will now see how to duplicate a list by using slicing.
dup2 = list1[:]
print(list1)
print(dup2)
dup2.remove(8)
print(list1)
print(dup2)
� Exercise
A list called Avengers
is provided in the cell below. Add code to accomplish the following tasks:
Avengers_Asc
and one called Avengers_Desc
. Avengers_Asc
in ascending alphabetical order. Avengers_Desc
in descending alphabetical order. Avengers = ['Capt. America', 'Black Widow', 'Iron Man', 'Hulk', 'Thor', 'Hawkeye']
Avengers_Asc = Avengers.copy()
Avengers_Desc = Avengers.copy()
Avengers_Asc.sort()
Avengers_Desc.sort()
Avengers_Desc.reverse()
print(Avengers_Asc)
print(Avengers_Desc)