Key Ideas
- A list is an ordered collection of items that can be of any type, e.g.
["Computer Science", 2017, 3.1415, False]
. - List creation
boys = ["Brady", "Jacob", "Quinn", "Tjabe", "Luke"]
girls = ["Aubrey", "Sarah", "Anya", "Maggie", "Eliana", "Addy"]
students = [boys, girls]
- Determining List Length:
len
- Accessing List Elements
boys[1]
students[1][2]
- List Membership:
in
andnot in
- List Concatenation:
+
- List Repetition:
*
- List Slices
girls[2:4]
girls[:2]
girls[2:]
- Lists are mutable (unlike Strings)
- Replacement:
boys[0] = "Seamus"
- Deletion:
boys[1:3] = []
- Deletion:
del(boys[0])
- Replacement:
- List Aliasing:
students = boys
- List Cloning:
students = boys[:]
Averages Problem
Write a function called average
that takes a list of numbers as a parameter and returns the average of the numbers.
def average(numbers):
total = 0
for number in numbers:
total += number
return total / len(numbers)
def average_2(numbers):
return sum(numbers) / len(numbers) # a much simpler (and more elegant) solution using the built-in sum() function
numbers = [1, 2, 3, 4, 5]
print(average(numbers))
Max Number Problem
Write a Python function named max
that takes a parameter containing a nonempty list of integers and returns the maximum value. (Note: there is a built-in function named max()
but pretend you cannot use it.)
def max_num(numbers):
biggest = 0
for item in numbers:
if item > biggest:
biggest = item
return biggest
def max_num2(numbers):
return max(numbers) # the illegal (but more elegant) solution using built-in max() function
numbers = [54, 23, 84, 57, 23, 90]
print(max_num(numbers))
HW:
Use the following code to answer the questions below:
boys = ["Brady", "Jacob", "Quinn", "Tjabe", "Luke"]
girls = ["Aubrey", "Sarah", "Anya", "Maggie", "Eliana", "Addy"]
students = [boys, girls]
- What output would the following commands create?
print(boys[2])
print(girls[3:])
print(students[0][0])
print(students[1][1:4])
- Explain the difference between these two commands:
students = boys
students = boys[:]
- What command could we use to add another boy, named “Seamus”, to the
boys
list?