An object is mutable if its contents can be changed after it is created, and immutable if they cannot. Numbers, strings and tuples are immutable, while lists, dictionaries and sets are mutable. The difference matters when objects are copied and passed to functions.

Creating Lists

A list is an ordered collection of items written in square brackets and separated by commas, such as marks = [72, 85, 60]. Items can be of different types, and a list can contain other lists. Items are reached by index from 0, and negative indices count from the end. Because a list is mutable, an item can be changed by assigning to its index, as in marks[1] = 90. Slicing works as it does for strings and gives a new list.

Definition: List. An ordered, mutable collection of items written in square brackets.

Common List Functions

The method append(x) adds an item at the end, insert(i, x) adds it at a position, extend(L) adds all items of another list, and remove(x) deletes the first occurrence of x. The method pop(i) removes and returns the item at index i, or the last item if no index is given. Others are sort(), reverse(), index(x) and count(x). The built-in functions len(), sum(), min(), max() and sorted() also work on lists. A list comprehension, such as [x * x for x in range(5)], builds a new list in one line.

Lists can also be nested, so a list of lists represents a table, as in grid = [[1, 2], [3, 4]], where grid[1][0] is 3. Two lists are compared item by item, and the operator in tests whether an item is present. The function list() converts another sequence, such as a string or a range, into a list. Since a list can grow and shrink freely, it is the most commonly used collection in Python programs, for example to hold the marks of students read from the user.

Table 3.1: Common list operations

Operation Purpose Example
append(x) Add at end L.append(5)
insert(i, x) Add at position L.insert(0, 9)
remove(x) Delete first x L.remove(5)
pop() Remove last item L.pop()
sort() Order in place L.sort()

Example 3.1: Working with a list of marks

Problem: For marks = [72, 85, 60, 91], add 78, remove 60, sort the list in descending order, and report the highest, lowest and average.

Solution:

  1. Use append(78) and remove(60).
  2. Use sort(reverse=True).
  3. Apply max(), min() and sum() / len().

Result: The sorted list is [91, 85, 78, 72], the highest is 91, the lowest is 72 and the average is 81.5.

marks = [72, 85, 60, 91]
marks.append(78)
marks.remove(60)
marks.sort(reverse=True)
print(marks, max(marks), min(marks), sum(marks) / len(marks))
print([x * x for x in range(5)], marks[1:3], marks[::-1])
a = marks
b = marks.copy()
a.append(0)
print(len(marks), len(b))

Output

[91, 85, 78, 72] 91 72 81.5
[0, 1, 4, 9, 16] [85, 78] [72, 78, 85, 91]
5 4

Common mistakes

  • Believing that b = a makes a copy. Both names refer to the same list.
  • Using remove() for an item that is not in the list, which raises ValueError.
  • Expecting sort() to return the sorted list. It sorts in place and returns None.

Key takeaways

  • Lists are ordered and mutable.
  • append, insert, remove and pop change a list in place.
  • b = a gives two names for one list, while a.copy() makes a new list.
  • A list comprehension builds a list in one line.

Practice questions

  1. Which of these are mutable: list, tuple, string, dictionary?
  2. What does pop() do?
  3. How is a copy of a list made?

Answers to the practice questions

  1. List and dictionary.
  2. Removes and returns the last item, or the item at a given index.
  3. With a.copy() or a[:].

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit III