Definition
How do you keep the marks of fifty students in one place?
A list is an ordered, changeable collection of items, written in square brackets, such as [72, 85, 64]. Items are accessed by index from 0, can be of any type, and can be added, removed, changed and sorted.
In simple words
A list is a row of numbered boxes in one variable. marks[0] is the first box. marks.append(90) adds a box at the end. len(marks) counts the boxes. sum(marks) / len(marks) is the average. Unlike a string, you can change any box.
Why it matters
Datasets are collections: rows of data, lists of words, batches of images. Lists are Python's basic collection, and NumPy arrays and pandas columns, used throughout AI, behave in similar ways.
How it works
| Operation | Example | Result for marks = [72, 85, 64] |
|---|---|---|
| Access | marks[1] | 85 |
| Change | marks[2] = 70 | [72, 85, 70] |
| Add to end | marks.append(90) | [72, 85, 64, 90] |
| Remove a value | marks.remove(85) | [72, 64] |
| Sort | sorted(marks) | [64, 72, 85] |
| Length, total, largest | len, sum, max | 3, 221, 85 |
In code
A marks list with average, topper and a sorted copy.
names = ["Aarav", "Meera", "Kabir", "Sana"]
marks = [72, 91, 64, 85]
print("Average:", sum(marks) / len(marks))
best = max(marks)
print("Topper:", names[marks.index(best)], "with", best)
marks.append(78)
names.append("Ishaan")
print("After adding Ishaan:", marks)
print("Sorted copy:", sorted(marks))
print("Original order kept:", marks)
print("Highest three:", sorted(marks, reverse=True)[:3])Output
Average: 78.0 Topper: Meera with 91 After adding Ishaan: [72, 91, 64, 85, 78] Sorted copy: [64, 72, 78, 85, 91] Original order kept: [72, 91, 64, 85, 78] Highest three: [91, 85, 78]
Try it yourself
Predict the list
Start each time from nums = [3, 1, 2]. What does each operation give?
- nums.append(5); nums
- sorted(nums)
- nums[0] = 9; nums
- len(nums)
- nums[-1]
Common mistakes
- Writing x = x.sort(), which sets x to None.
- Using an index that is too big: IndexError.
- Copying with b = a and being surprised that changing b changes a. Use a.copy().
Check yourself
Summary
- Lists are ordered, changeable collections in square brackets.
- append, remove, sort, len, sum and max cover most needs.
- sorted() returns a new list; .sort() changes the original.
Finished reading?
Sources: Python docs: Data Structures