Mastering Python Lists & List Methods
Lists are Python's most-used data structure — ordered, mutable, and capable of holding anything. From storing user records to building queues, every Python developer touches lists daily. In this lesson you'll learn the entire list API, list comprehensions, and the performance characteristics that matter in real code.
Overview
Ordered & Indexed
Items keep insertion order and are accessible by index.
Mutable
Add, remove, and replace items at will.
Heterogeneous
Hold numbers, strings, objects — even other lists.
Comprehensions
Express filters and maps in a single readable line.
Fast Access
O(1) indexing, amortised O(1) append.
Syntax
- Create with
[]orlist(). - Access with indices:
lst[0],lst[-1], sliceslst[1:4]. - Mutate with
append,extend,insert,remove,pop. - Transform with
sort,reverse, comprehensions,map,filter.
nums = [3, 1, 4, 1, 5, 9, 2, 6] nums.append(5) # add at end nums.insert(0, 99) # add at index nums.remove(1) # remove first 1 last = nums.pop() # remove & return last nums.sort() # sort in place nums.reverse() # reverse in place squares = [x*x for x in nums] # comprehension
Detailed Explanation
- Lists are mutable: Unlike strings, lists can be modified in place. Method calls like
appendchange the original list and returnNone. - Indexing and slicing: Indices start at 0; negative indices count from the end. Slices
lst[a:b:s]create new lists; modifications to the slice don't affect the original. - Add elements:
append(x)adds one item;extend(iter)appends all items of an iterable;insert(i, x)places x at index i (slower for big lists). - Remove elements:
remove(x)deletes the first match;pop(i)removes and returns item i (default last);del lst[i]deletes by index;clear()empties. - Search & count:
intests membership;index(x)returns position (or raises);count(x)tells how many times x appears. - Sorting:
sort()sorts in place;sorted(lst)returns a new sorted list. Both acceptkey=andreverse=. - Comprehensions:
[expr for x in iter if cond]— concise, fast, idiomatic. Replaces many for-loops + appends with a single expression.
Code Examples
fruits = ["apple", "banana", "cherry", "date"] print(fruits[0]) print(fruits[-1]) print(fruits[1:3])
date
['banana', 'cherry']
lst = [1, 2, 3] lst.append(4) lst.extend([5, 6]) lst.insert(0, 0) lst.remove(3) print(lst)
nums = [3, 1, 4, 1, 5, 9, 2, 6] nums.sort() print(nums) nums.sort(reverse=True) print(nums)
[9, 6, 5, 4, 3, 2, 1, 1]
evens_squared = [x*x for x in range(10) if x % 2 == 0] print(evens_squared)
people = [("Riya", 22), ("Sam", 19), ("Anu", 31)]
print(sorted(people, key=lambda p: p[1]))
mat = [[1, 2], [3, 4], [5, 6]] flat = [x for row in mat for x in row] print(flat)
Real-World Use Cases
Shopping Carts
Add/remove products dynamically as the user shops.
Task Queues
Use list-based queues for simple work scheduling.
Data Loading
Load rows from a CSV into a list of records for processing.
Randomisation
Use random.shuffle to randomise quiz questions.
Recommendation Systems
Filter and sort items based on user preferences.
Logging
Append log entries to a list, then persist them in batches.
Notes & Pro Tips
- Use
appendin loops, not+— concatenation creates a new list every time. - Use
list comprehensionsovermap+filterfor readability. - Prefer
sorted()when you need a new sorted copy;sort()for in-place. - Use
collections.dequefor fast popleft on the left side. list1 = list2creates an alias; uselist1 = list2[:]orlist(list2)to copy.- For large numeric data, use NumPy arrays — they're much faster than Python lists.
Common Mistakes
- Iterating while mutating: skips items or raises errors; iterate over a copy.
- Assuming sort() returns the list: it returns
None— usesorted(). - Confusing append with extend:
append([1,2])adds the list as one element. - Slicing copy assumption: shallow copies share nested objects.
- Using list as default arg: shared across calls — surprising bug.
- Inefficient prepending:
lst.insert(0, x)is O(n); use deque for fast left-end ops.
Practice Problems
- Problem 1: Read 10 numbers and print the sum, average, max, min and median.
- Problem 2: Remove duplicates from a list while preserving order.
- Problem 3: Merge two sorted lists into one sorted list.
- Problem 4: Rotate a list by k positions to the right.
- Problem 5: Find the second-largest element without using sort().
- Problem 6: Group a list of strings by length using a dictionary.
Interview Questions
- Q1. What is the difference between
append()andextend()? - Q2. How do you remove duplicates from a list while preserving order?
- Q3. What is the time complexity of
list.index(x)andx in list? - Q4. What is a shallow copy vs a deep copy?
- Q5. Why is
insert(0, x)slow on large lists? - Q6. Explain list comprehensions and when they're preferable to loops.
Frequently Asked Questions
- Q1: How do I copy a list?
Use list2 = list1[:] or list(list1). For nested lists use copy.deepcopy(). - Q2: What's the difference between append and extend?
append adds one item; extend appends each element of an iterable. - Q3: How do I sort a list of dicts by a key?
Use sorted(list_of_dicts, key=lambda d: d['name']). - Q4: Why does sort() return None?
Because it sorts in place. Use sorted() to receive a new sorted list. - Q5: Are lists faster than arrays?
For mixed-type sequences, yes. For numeric vectorised math, NumPy arrays are much faster. - Q6: How do I flatten a nested list?
Use a comprehension: [x for sub in nested for x in sub], or itertools.chain.from_iterable.
Summary
Lists are Python's swiss-army knife for ordered data. With append, extend, slicing, sorting, and comprehensions, you can express almost any algorithm in a few lines. Remember the small but crucial gotchas — in-place vs returning, shallow vs deep copy, and the O(n) cost of prepending — and you'll write fast, idiomatic Python every time.
Continue Learning
Previous
Go to Previous Chapter