Lists and Tuples
Ordered sequences in Python: the mutable list and the immutable tuple.
Lists
scores = [0.82, 0.91, 0.77]
scores.append(0.88) # add at the end
scores.insert(0, 0.5) # add at a given position
scores.remove(0.77) # remove a value
last = scores.pop() # remove the last element and return it
scores.sort() # sort ascending in place
len(scores) # number of elementsIndexing and slicing
x = [10, 20, 30, 40, 50]
x[0] # 10
x[-1] # 50
x[1:4] # [20, 30, 40]
x[:2] # [10, 20]
x[::2] # [10, 30, 50]
x[::-1] # reverse the listThe index starts at zero, and the end of a slice is not included.
Copying versus referencing
a = [1, 2, 3]
b = a # b refers to the same list
b.append(4)
print(a) # [1, 2, 3, 4]
c = a.copy() # an independent (shallow) copyTuples
shape = (224, 224, 3) # image dimensions
h, w, c = shape # unpacking
def min_max(values):
return min(values), max(values) # returns a tuple
lo, hi = min_max([3, 9, 1])Tuples are lighter than lists, and they can be used as dictionary keys because they are immutable (if their elements are too).
Useful functions
sum andmin andmax andsorted (returns a new list) andany andall. Example: sorted(scores, reverse=True)[:3] returns the three highest scores.
Lesson terms
- Tokenization
- Extracting part of a sequence with the form [start:stop:step].
- Tuple
- An ordered, immutable sequence written between ordinary parentheses.
- List
- An ordered, mutable sequence of elements written between square brackets.
Abstract
A list is a mutable ordered sequence that supports adding, removing, sorting and slicing, and a tuple is an immutable ordered sequence used for fixed values and for returning several values from a function. Both are indexed from zero and support negative indices and slicing.
Review questions
-
What is the result of [10, 20, 30, 40][1:3]?
[20, 30].
-
When do you use a tuple instead of a list?
When the values are fixed and should not be changed, such as image dimensions or coordinates, or as a dictionary key.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate