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.
Overview
- A list is an ordered, mutable collection written in square brackets: [10, 20, 30].
- Lists can hold any types, even mixed, and can contain other lists.
- Indexing and slicing work exactly as for strings, but lists can be changed in place.
- len(), sum(), min(), max() and sorted() work on lists of numbers.
- Assigning a list to a new name does not copy it; use .copy() or list() for an independent copy.
- Lists are Python's everyday container for rows of data, before moving to NumPy arrays.
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.
Key terms
- List
- An ordered, changeable collection written in square brackets.
- Element
- One item in a list.
- Mutable
- Can be changed in place after creation.
- append()
- Adds one item to the end of a list.
- Aliasing
- Two names referring to the same list, so a change through one shows through the other.
- Nested list
- A list whose items are lists, often used for tables or grids.
Types
List operations fall into families by what they do to the list. Knowing the families helps you pick the right method quickly.
1. Adding items: append, insert, extend
Methods that put new items into a list.
- How it works: append(x) adds one item at the end; insert(i, x) adds at position i; extend(other) adds every item of another list.
- Example: marks.append(88); marks.insert(0, 75); marks.extend([60, 92]).
- When to use it: Use append to build lists in loops, insert for a specific position and extend to join lists.
2. Removing items: remove, pop, del, clear
Ways to take items out of a list.
- How it works: remove(x) deletes the first matching value; pop(i) removes and returns the item at i (the last by default); del list[i] or a slice deletes by position; clear() empties it.
- Example: queue.pop(0) takes the first person; names.remove("Ravi") removes Ravi.
- When to use it: Use remove when you know the value, pop when you need the removed item, and del for positions or slices.
3. Ordering: sort, sorted, reverse
Ways to arrange a list's items.
- How it works: list.sort() changes the list in place; sorted(list) returns a new sorted list; both accept reverse=True and a key function; reverse() flips the order.
- Example: students.sort(key=lambda s: s[1], reverse=True) ranks by marks.
- When to use it: Use sort() when the original order is no longer needed and sorted() when it is.
4. Searching and counting: in, index, count
Ways to find whether and where a value appears.
- How it works: x in list returns True or False; list.index(x) gives the first position (or ValueError); list.count(x) counts occurrences.
- Example: "Delhi" in cities; votes.count("Yes").
- When to use it: Use them for quick checks on small lists; for many lookups, a set or dictionary is much faster.
5. Nested (2D) lists
Lists whose items are themselves lists, forming rows and columns.
- How it works: grid[r][c] reaches row r, column c; nested loops visit every cell; create rows with a comprehension, not [[0] * 3] * 3, which repeats the same row object.
- Example: A marks table: [["Asha", 78, 85], ["Ravi", 66, 72]].
- When to use it: Use them for small tables, boards and matrices; switch to NumPy or pandas for large data.
Explained in detail
Lists are the workhorse
A list holds any number of items in order, of any type, and can grow, shrink and change. That flexibility makes it Python's most used collection: a list of marks, of names, of sentences, of predictions. Lists support indexing and slicing exactly like strings, but unlike strings they are mutable, so marks[0] = 80 changes the first item in place. Many functions work on lists directly: len(), sum(), min(), max() and sorted().
Adding and removing
| Method | Effect | Note |
|---|---|---|
| append(x) | Add x at the end | The most common way to grow a list |
| insert(i, x) | Add x at position i | Slower for long lists, as items shift |
| extend(other) | Add every item of another list | append(other) would add the whole list as one item |
| remove(x) | Remove the first x | ValueError if x is absent |
| pop(i) | Remove and return the item at i | pop() with no index removes the last |
| del items[i] | Delete by position or slice | del items[1:3] removes two items |
The aliasing trap
Because variables are labels, b = a does not copy a list; it gives the same list a second name. After b.append(99), a also contains 99. This surprises almost every learner once. When you need an independent copy, write b = a.copy() or b = a[:]. For a list of lists, even that copy shares the inner lists; use copy.deepcopy() for a completely separate copy. The same applies when you pass a list into a function: if the function changes it, the caller sees the change.
Lists of lists
A table can be stored as a list of rows, each row a list: grid = [[1, 2, 3], [4, 5, 6]]. grid[1][2] is 6, row 1, column 2. Beware of building a grid with [[0] * 3] * 2: this creates two references to the same inner row, so changing one cell changes both rows. Build it with a comprehension instead, as you will see later. In data science, large tables are usually handled by NumPy arrays and pandas DataFrames, which are faster and safer, but they build on the same row-and-column thinking.
- x in items checks membership, but for long lists it is slow; sets are much faster.
- items.index(x) finds a position; items.count(x) counts occurrences.
- items.sort(reverse=True) sorts from largest to smallest.
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