Learning Objectives – after this chapter you will be able to:
  • Create lists and access items with positive and negative indexes.
  • Slice lists with [start:stop:step].
  • Add, remove, search and sort items using list methods.
  • Copy lists correctly and write list comprehensions.
What is a List?
  • A list is an ordered, mutable collection written in square brackets: [10, 20, 30].
  • It can hold items of different types and allows duplicates; a list can even contain other lists (nested lists).
  • Items are accessed by index, starting at 0. Negative indexes count from the end: -1 is the last item.
marks = [78, 92, 65, 88, 70]
mixed = ["Asha", 21, 5.6, True]
empty = []
print(marks[0], marks[2], marks[-1], marks[-2])
print(len(marks), len(empty))
print(mixed)

matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2])          # row 1, column 2
Output
78 65 70 88
5 0
['Asha', 21, 5.6, True]
6
Slicing

list[start:stop:step] returns a new list from start up to, but not including, stop.

nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[:3])
print(nums[3:])
print(nums[::2])
print(nums[::-1])     # reversed copy
print(nums[-3:])
Output
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
[40, 50, 60]
Common List Methods
MethodAction
append(x)Add x at the end.
insert(i, x)Insert x at position i.
extend(iterable)Add all items of another iterable.
remove(x)Remove the first occurrence of value x (ValueError if absent).
pop(i)Remove and return the item at index i (last item by default).
clear()Remove all items.
index(x)Position of the first x.
count(x)Number of times x appears.
sort()Sort the list in place (returns None).
reverse()Reverse the list in place.
copy()Return a shallow copy.
items = ["pen", "book"]
items.append("bag")
items.insert(1, "ink")
items.extend(["cap", "pen"])
print(items)

items.remove("pen")          # removes the FIRST "pen"
last = items.pop()
print(items, "| popped:", last)
print(items.index("bag"), items.count("cap"))

del items[0]                 # delete by index
items[0] = "notebook"        # lists are mutable
print(items)
Output
['pen', 'ink', 'book', 'bag', 'cap', 'pen']
['ink', 'book', 'bag', 'cap'] | popped: pen
2 1
['notebook', 'bag', 'cap']
Sorting: sort() vs sorted()
scores = [45, 12, 78, 33]
new_list = sorted(scores)            # returns a NEW sorted list
print(new_list, scores)

scores.sort(reverse=True)            # changes the list itself
print(scores)

words = ["banana", "kiwi", "apple", "Cherry"]
print(sorted(words))                 # uppercase letters sort first
print(sorted(words, key=str.lower))  # case-insensitive
print(sorted(words, key=len))        # by length
Output
[12, 33, 45, 78] [45, 12, 78, 33]
[78, 45, 33, 12]
['Cherry', 'apple', 'banana', 'kiwi']
['apple', 'banana', 'Cherry', 'kiwi']
['kiwi', 'apple', 'banana', 'Cherry']
Copying a List

Assignment (b = a) does not copy – both names refer to the same list. Use a.copy(), list(a) or a[:] for a shallow copy. For nested lists use copy.deepcopy().

a = [1, 2, 3]
b = a            # same list
c = a.copy()     # new list
a.append(4)
print(b, c)

import copy
nested = [[1, 2], [3, 4]]
shallow = nested.copy()
deep = copy.deepcopy(nested)
nested[0].append(99)
print(shallow, deep)
Output
[1, 2, 3, 4] [1, 2, 3]
[[1, 2, 99], [3, 4]] [[1, 2], [3, 4]]
List Comprehension and Useful Functions

A list comprehension builds a list in one line: [expression for item in iterable if condition].

squares = [n * n for n in range(1, 6)]
evens = [n for n in range(1, 11) if n % 2 == 0]
print(squares)
print(evens)

data = [12, 7, 25, 3]
print(sum(data), min(data), max(data), sum(data) / len(data))
print(25 in data)
print([1, 2] + [3], [0] * 3)
Output
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
47 3 25 11.75
True
[1, 2, 3] [0, 0, 0]
Key Takeaways
  • Lists are ordered, mutable and allow duplicates; indexing starts at 0.
  • sort() changes the list and returns None; sorted() returns a new list.
  • b = a shares the list; use copy() or deepcopy() to duplicate it.
Video : Lists
Question / Answer (15 questions)

Answer : A list is an ordered, mutable collection of items written inside square brackets. It can store items of different types, allows duplicate values and can be nested.

Answer : Positive indexes start at 0 from the left; negative indexes start at -1 from the right. For marks = [78, 92, 65, 88, 70], marks[0] is 78 and marks[-1] is 70.

Answer : [20, 30, 40] – the items from index 1 up to, but not including, index 4.

Answer : list.reverse() reverses it in place; slicing with list[::-1] returns a new reversed list; reversed(list) returns a reverse iterator.

Answer : append(x) adds x as a single item at the end – appending [3, 4] adds one nested list. extend(iterable) adds each item of the iterable separately – extending with [3, 4] adds 3 and 4.

Answer : remove(x) deletes the first occurrence of a value. pop(i) deletes and returns the item at index i (last item by default). del list[i] deletes by index or slice without returning anything.

Answer : list.sort() sorts the list in place and returns None. sorted(iterable) returns a new sorted list and leaves the original unchanged; it also works on any iterable.

Answer : Use list.sort(reverse=True) or sorted(list, reverse=True).

Answer : key is a function applied to each item to produce the value used for comparison. sorted(words, key=len) sorts by length and key=str.lower sorts case-insensitively.

Answer : Assignment copies only the reference. Both names point to the same list object, so changing the list through one name is visible through the other. Use a.copy(), list(a) or a[:] to create a new list.

Answer : A shallow copy creates a new outer list but shares the inner (nested) objects. A deep copy, made with copy.deepcopy(), recursively copies all nested objects so changes to inner lists do not affect the copy.

Answer : A concise way to build a list: [expression for item in iterable if condition]. Example: [n * n for n in range(1, 6)] gives [1, 4, 9, 16, 25].

Answer : Divide the sum by the number of items: sum(data) / len(data). For [12, 7, 25, 3] the average is 11.75.

Answer : Python raises ValueError. Check membership first with if x in my_list: or handle the exception.

Answer : Use two indexes – the first selects the inner list (row) and the second selects the item (column). matrix[1][2] is 6.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What is the output of print([10, 20, 30, 40][-2])?

Show Answer

Correct Answer : B. 30
-1 is 40, so -2 is 30.

Q2. What does list.sort() return?

Show Answer

Correct Answer : C. None
sort() sorts in place and returns None.

Q3. Which method removes and RETURNS the last item of a list?

Show Answer

Correct Answer : A. pop()
pop() without an index removes and returns the last item.

Q4. What is the output of print([n for n in range(5) if n % 2])?

Show Answer

Correct Answer : D. [1, 3]
n % 2 is truthy only for odd numbers 1 and 3.

Q5. a = [1, 2]; b = a; b.append(3). What is a?

Show Answer

Correct Answer : B. [1, 2, 3]
a and b refer to the same list object.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Python Software Foundation. (n.d.). An Informal Introduction to Python. In The Python Tutorial. https://docs.python.org/3/tutorial/introduction.html
  2. Python Software Foundation. (n.d.). Data Structures. In The Python Tutorial. https://docs.python.org/3/tutorial/datastructures.html
  3. Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
  4. Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
  5. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
  6. Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.