Skip to content
CodeNest

Data StructuresLesson 9 of 1916 min

Lists

Ordered, changeable collections — the workhorse container of Python.

By the end you will be able to

  • Create, index, and slice lists
  • Add and remove items with append, insert, pop, and remove
  • Sort and reverse lists, in place or into a copy

A list holds many values in order, written in square brackets. Items can be of any type, and — unlike strings — a list can be changed after it is created.

Python
Output
[88, 92, 79, 95, 61]
5
88 61
[92, 79]
— expected output; press Run to execute it yourself

Lists are mutable

You can assign straight into an index, which is the key difference from strings.

Python
Output
['red', 'lime', 'blue']
['amber', 'red', 'lime', 'blue', 'violet']
violet ['amber', 'red', 'lime', 'blue']
['amber', 'red', 'blue']
— expected output; press Run to execute it yourself
Python
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 1, 2]
— expected output; press Run to execute it yourself

Sorting

.sort() reorders the list in place and returns None. sorted() leaves the original alone and returns a new sorted list. Confusing the two is a classic beginner bug.

Python
Output
[61, 79, 88, 92, 95]
[88, 92, 79, 95, 61]
[95, 92, 88, 79, 61]
['Alpha', 'charlie', 'delta']
95 61 415
— expected output; press Run to execute it yourself
Python
Output
[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 99]
— expected output; press Run to execute it yourself

Exercise

Write a function top_three(scores) that returns a new list of the three highest scores, highest first. The original list must not be modified.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.What does [1, 2, 3].append([4, 5]) produce?
  2. 2.What does scores.sort() return?
  3. 3.After b = a where a = [1, 2], then b.append(3), what is a?