What is a Python List?
Key Characteristics
- Ordered – Maintains insertion order
- Mutable – Can be modified after creation
- Heterogeneous – Can store different data types
- Dynamic – Automatically resizes as needed
- Indexable – Access elements via integer indices
Real-World Analogy
Think of a Python list like a shopping cart – items stay in the order you add them, you can add/remove items anytime, and you can put different types of items together.
# Basic list creation nums = [1, 2, 3] mixed = [1, "hello", 3.14, [4, 5]] # Nested lists (2D array) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # List of dictionaries students = [ {"name": "Alice", "grade": 95}, {"name": "Bob", "grade": 87} ] # Type checking print(type(nums)) # <class 'list'> print(len(mixed)) # 4 print(isinstance(matrix, list)) # True
Creating Lists in Python
Basic Creation Methods
Empty Lists
a = [] # Recommended b = list() # Using constructor
From Other Iterables
c = list((1, 2, 3)) # From tuple d = list(range(5)) # [0, 1, 2, 3, 4] e = list("hello") # ['h', 'e', 'l', 'l', 'o']
Common Pitfall
list = []
overwrites the built-in list function!
Always use meaningful variable names like my_list or numbers.
Advanced Initialization
List Multiplication
zeros = [0] * 5 # [0, 0, 0, 0, 0] repeated = ["hi"] * 3 # ['hi', 'hi', 'hi'] # Warning: For mutable objects! matrix = [[0]] * 3 # All refer to same list! matrix[0][0] = 1 # Changes all rows
From Generators
# Using list comprehension (later section) squares = [x*x for x in range(5)] # From generator expression gen = (x for x in range(10) if x%2==0) evens = list(gen)
Complete List Methods Reference
| Method | Description | Time Complexity | Example |
|---|---|---|---|
append(x) |
Adds single element to end | O(1) | lst.append(4) |
extend(iterable) |
Adds all elements from iterable | O(k) | lst.extend([5,6]) |
insert(i, x) |
Insert at specific index | O(n) | lst.insert(1, "a") |
remove(x) |
Remove first occurrence of value | O(n) | lst.remove(3) |
pop([i]) |
Remove & return element at index (default last) | O(1) for last, O(n) otherwise | last = lst.pop() |
clear() |
Remove all elements | O(1) | lst.clear() |
index(x, [start, [end]]) |
Return index of first occurrence | O(n) | i = lst.index("apple") |
count(x) |
Count occurrences of value | O(n) | c = lst.count(2) |
sort(key=None, reverse=False) |
Sort list in-place (TimSort) | O(n log n) | lst.sort(reverse=True) |
reverse() |
Reverse elements in-place | O(n) | lst.reverse() |
copy() |
Return shallow copy | O(n) | new = lst.copy() |
len() |
Get number of elements | O(1) | length = len(lst) |
min() / max() |
Get smallest/largest element | O(n) | smallest = min(lst) |
sum() |
Sum all elements (numeric) | O(n) | total = sum(lst) |
any() / all() |
Check if any/all are truthy | O(n) | has_true = any(lst) |
Advanced List Comprehensions
Comprehension Patterns
Basic Pattern
# [expression for item in iterable] squares = [x*x for x in range(5)] # [0, 1, 4, 9, 16]
With Condition
# [expression for item in iterable if condition] evens = [x for x in range(10) if x%2==0] # [0, 2, 4, 6, 8]
Nested Comprehensions
# Flatten 2D list matrix = [[1,2], [3,4], [5,6]] flat = [n for row in matrix for n in row] # [1, 2, 3, 4, 5, 6]
Advanced Examples
Dictionary Comprehension
# Create dict from list names = ["Alice", "Bob", "Charlie"] name_dict = {name: len(name) for name in names} # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
Conditional Expression
# Ternary in comprehension numbers = [1, 2, 3, 4, 5] result = ["even" if x%2==0 else "odd" for x in numbers] # ['odd', 'even', 'odd', 'even', 'odd']
Set Comprehension
# Remove duplicates while transforming numbers = [1, 2, 2, 3, 3, 3] unique_squares = {x*x for x in numbers} # {1, 4, 9}
Performance & Best Practices
Time Complexity Guide
Constant time: lst[0], lst[-1]
*Amortized constant time
All elements must shift
x in lst)
O(n)
Linear scan required
Best Practices & Alternatives
Use deque for queues
When you need efficient insertion/deletion at both ends
from collections import deque queue = deque([1, 2, 3]) queue.append(4) # O(1) queue.popleft() # O(1)
Use sets for membership tests
Convert to set if checking membership many times
lst = [1, 2, 3, 4, 5] s = set(lst) # O(n) once if 3 in s: # O(1) many times print("Found")
List vs Tuple: When to Use Which?
| Feature | List | Tuple | Recommendation |
|---|---|---|---|
| Syntax | [1, 2, 3] |
(1, 2, 3) |
Lists use [], tuples use () |
| Mutability | Mutable | Immutable | Use lists for changing data, tuples for constants |
| Performance | Slower for iteration | Faster (up to 5x) | Tuples for large read-only data |
| Memory Usage | More memory | Less memory | Tuples for memory-constrained applications |
| Use Case | Shopping cart, to-do list | Days of week, RGB colors | Lists: dynamic collections; Tuples: records |
| Hashable | No (can't be dict key) | Yes (if all elements are) | Tuples can be dictionary keys |
| Methods | Many (append, remove, sort...) | Few (count, index only) | Lists for frequent modifications |
Practical List Assignments
Test your understanding with these practical exercises. Try to solve them without looking at solutions first!
1. Basic Operations
Create a list of 10 numbers. Find the sum, average, maximum, and minimum without using built-in functions.
2. List Manipulation
Given two lists, merge them, remove duplicates, and sort in descending order using only list methods.
3. List Comprehension
Generate a list of prime numbers between 1-100 using list comprehension with a helper function.
4. Matrix Operations
Implement matrix addition and multiplication using nested lists. Handle different dimensions.
5. Performance Challenge
Compare three methods for removing duplicates from a list of 1 million integers. Measure execution time.
6. To-Do List Manager
Build a command-line to-do list with add, remove, mark complete, list, and priority features.