Computer Science · Ch 9 — Lists
Introduction to List
Introduction to List
A list is Python's workhorse container: an ordered sequence of values that is mutable, meaning its contents can be changed after it is created. A list is made up of one or more elements, and — unlike a string, which can hold only characters — a list may freely mix elements of different data types: integers, floats, strings, tuples, and even other lists. This makes a list the natural choice whenever you need to group together related items of mixed types under one name.
Writing a list
The syntax rules are simple:
- The elements are enclosed in square brackets
[ ]. - The elements are separated by commas.
- Like string indices, list indices start from 0 — the first element is at index 0, the second at index 1, and so on.
Lists of a single data type
A list often holds values that are all of one type, such as numbers or characters:
# a list of five multiples of 3
>>> marks = [3, 6, 9, 12, 15]
>>> print(marks)
[3, 6, 9, 12, 15]
# a list of single-character strings
>>> letters = ['p', 'q', 'r', 's']
>>> print(letters)
['p', 'q', 'r', 's']
Lists of mixed data types
The same list can combine an integer, a float and a string without any special handling:
# a list holding an int, a float and a string
>>> record = [7, 68.5, 'Pass']
>>> print(record)
[7, 68.5, 'Pass']
A list inside a list — the nested list
When one of the elements of a list is itself a list, the outer list is called a nested list. This is useful for keeping small groups of related values together, such as a subject name paired with its course code:
# each element is itself a two-element list
>>> courses = [['Biology', 401], ['History', 502], ['Music', 603]]
>>> print(courses)
[['Biology', 401], ['History', 502], ['Music', 603]]
Here courses has three elements, and each element is a two-item list. Nested lists are explored in detail later in the chapter (Section 9.5).
What the rest of the chapter covers
Having defined what a list is and how to create one, the chapter builds up the full toolkit for working with lists: accessing individual elements by index (9.1.1), changing elements in place because lists are mutable (9.1.2), the list operations of concatenation, repetition, membership and slicing (9.2), visiting every element with loops (9.3), the built-in list methods and functions (9.4), nested lists (9.5), the right and wrong ways to copy a list (9.6), what happens when a list is passed to a function (9.7), and finally complete programs that put these manipulations to work (9.8).