Lists are Python's workhorse collection — ordered, mutable, can hold anything. They're also the gateway to one of Python's best features: list comprehensions.
Creating lists
# Literalfruits = ["apple", "mango", "banana"]# Empty list — two equivalent waysempty = []empty2 = list()# From an iterablechars = list("hello") # ['h', 'e', 'l', 'l', 'o']nums = list(range(5)) # [0, 1, 2, 3, 4]# Mixed types — Python doesn't caremixed = [1, "two", 3.0, True, None]
Indexing & slicing
fruits = ["apple", "mango", "banana", "kiwi", "guava"]print(fruits[0]) # apple — firstprint(fruits[-1]) # guava — lastprint(fruits[2]) # banana — third# Slicing: [start:stop:step] stop is exclusiveprint(fruits[1:3]) # ['mango', 'banana']print(fruits[:2]) # ['apple', 'mango']print(fruits[2:]) # ['banana', 'kiwi', 'guava']print(fruits[::-1]) # reversed copyprint(fruits[::2]) # every other element
List methods
| Method | Effect |
|---|---|
| append(x) | add x to the end |
| insert(i, x) | insert x at index i |
| extend(iterable) | add all items from iterable |
| remove(x) | remove first occurrence of x |
| pop(i=-1) | remove and return item at i (last by default) |
| index(x) | return index of first x (raises if missing) |
| count(x) | count occurrences of x |
| sort() | sort in place |
| reverse() | reverse in place |
| clear() | empty the list |
scores = [70, 85, 90]scores.append(75) # [70, 85, 90, 75]scores.insert(0, 100) # [100, 70, 85, 90, 75]scores.extend([60, 95]) # [100, 70, 85, 90, 75, 60, 95]scores.remove(70) # [100, 85, 90, 75, 60, 95]last = scores.pop() # 95 scores: [100, 85, 90, 75, 60]first = scores.pop(0) # 100 scores: [85, 90, 75, 60]print(scores.count(85)) # 1print(scores.index(75)) # 2
Iterating over lists
fruits = ["apple", "mango", "banana"]# Plainfor f in fruits:print(f)# With indexfor i, f in enumerate(fruits):print(i, f)# Two lists in lockstepprices = [120, 80, 50]for f, p in zip(fruits, prices):print(f"{f}: ₹{p}")
List comprehensions
The single most-loved Python feature. Create a list by transforming/filtering an iterable in one expression:
# Squares of numbers 0-9squares = [n * n for n in range(10)]# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# Even numbers onlyevens = [n for n in range(10) if n % 2 == 0]# [0, 2, 4, 6, 8]# Apply a transform with filterprices_inr = [80, 120, 250, 400]discounted = [p * 0.9 for p in prices_inr if p > 100]# [108.0, 225.0, 360.0]# Strings — uppercase only the long fruit namesfruits = ["apple", "kiwi", "banana", "fig"]loud = [f.upper() for f in fruits if len(f) > 4]# ['APPLE', 'BANANA']
Nested lists
# A 3x3 matrixmatrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]# Access row 1, column 2print(matrix[1][2]) # 6# Iteratefor row in matrix:for val in row:print(val, end=" ")print()# Build with nested comprehensionidentity = [[1 if i == j else 0 for j in range(4)] for i in range(4)]
Sorting & reversing
nums = [3, 1, 4, 1, 5, 9, 2, 6]# In placenums.sort() # [1, 1, 2, 3, 4, 5, 6, 9]nums.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]# Returns a new list — original untouchedsorted_copy = sorted(nums)# Sort with a keyfruits = ["apple", "fig", "banana"]fruits.sort(key=len) # by length: ['fig', 'apple', 'banana']# Sort dicts by a fieldpeople = [{"name": "A", "age": 30}, {"name": "B", "age": 22}]people.sort(key=lambda p: p["age"])
Common gotchas
1. Multiplying lists copies references
# This looks like 3 separate rows, but…grid = [[0] * 3] * 3grid[0][0] = 1print(grid)# [[1, 0, 0], [1, 0, 0], [1, 0, 0]] ← all rows share the same list!# Correct — build with a comprehensiongrid = [[0] * 3 for _ in range(3)]grid[0][0] = 1print(grid)# [[1, 0, 0], [0, 0, 0], [0, 0, 0]] ← independent rows
2. Modifying a list while iterating
# ⚠️ Don't do thisnums = [1, 2, 3, 4]for n in nums:if n % 2 == 0:nums.remove(n)print(nums) # [1, 3] — but unreliable; some elements get skipped# ✅ Build a new listnums = [n for n in nums if n % 2 != 0]
Key takeaways
- 01Lists are ordered, mutable, can hold anything. Use square brackets or list().
- 02Slicing returns a new list — [::-1] is the canonical "reverse a list" idiom.
- 03Methods like append, insert, extend modify in place; sorted() and slicing return copies.
- 04List comprehensions are the standard tool — faster, more readable than manual loops.
- 05Never multiply a list of lists — use [[0]*N for _ in range(M)] for nested grids.
- 06Don't mutate a list while iterating it — build a new list instead.
