Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A list is a data structure used to store an ordered sequence of elements (values).

a = [3, 1, 2 * 2, 1, 10 / 2, 10 - 1]
b = [5, 3, "hi"]
c = [4, "a", a]
d = [[1, 2], [3, 4], [5, 6]]
e = [] # An empty list

Retrieve information about a list and its elements using built-in list operators and list functions:

Practice: Slicing and dicing

For each expression below, what would Python display?

a = [3, 12, 10, 7, 9, 7]
a[0]
a[5]
a[6]
a[-1]
a[-2]
a[1:3]
a[2:5]
a[:]
a[0:len(a)]

Using a = [2, 7, 3, 9, 4], write a Python expression to print 9 4 7.

Practice: Query this

For each expression below, what would Python display?

a = [3, 12, 10, 7, 9, 7]
9 in a
16 in a
a.index(7)
a.index(16)
a.count(7)
a.count(16)

Modifying list elements

There are many ways to modify the elements of a list. We can add elements to a list.

We can remove elements from a list.

We can replace elements in a list.

We can rearrange list elements.

Practice: Insertion

What would Python display?

lst = [1, 3, 5]
lst.insert(2, [4, 6])
lst[2]

Practice: Removing and replacing

For each code snippet, explain each step in Python Tutor.

lst = [1, 2, 3, 4, 5, 6, 7]
print(lst.pop())
print(lst.pop(1))
lst.remove(3)
lst[3] = "blue"
lst[1:3] = [10, 11, 12]
lst = [10, 12, 23, 54, 15]
lst.append(7)
lst.extend([8, 9, 3])
lst.insert(2, 2.75)
lst.remove(3)
print(lst.pop())
print(lst.pop(4))
lst[1:5] = [20, 21, 22]
lst2 = [4, 6, 8, 2, 0]
lst2.sort()
lst2.reverse()
lst3 = lst2
lst4 = lst2[:]
lst2[-1]= 17