Python for Artificial Intelligence Intermediate 12 minutes

Lists and Tuples

Ordered sequences in Python: the mutable list and the immutable tuple.

Your progress in the track0%

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 elements

Indexing 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 list

The 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) copy

Tuples

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

  1. What is the result of [10, 20, 30, 40][1:3]?

    [20, 30].

  2. 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

  1. Data Structures: More on Lists — Python documentation
  2. Tuples and Sequences — Python documentation

Complete the lesson