- 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:
-1is 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
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:])
[20, 30, 40] [10, 20, 30] [40, 50, 60] [10, 30, 50] [60, 50, 40, 30, 20, 10] [40, 50, 60]
Common List Methods
| Method | Action |
|---|---|
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)['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
[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)
[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)
[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 = ashares the list; usecopy()ordeepcopy()to duplicate it.
Video : Lists
Question / Answer (15 questions)
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.
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.
- Python Software Foundation. (n.d.). An Informal Introduction to Python. In The Python Tutorial. https://docs.python.org/3/tutorial/introduction.html
- Python Software Foundation. (n.d.). Data Structures. In The Python Tutorial. https://docs.python.org/3/tutorial/datastructures.html
- Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
- Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
- Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
- Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.