Overview
Lists are Python's most versatile and commonly used data structure. They are ordered, mutable sequences that can contain elements of different types.
Creating Lists
PYTHON
# Empty list
empty_list = []
empty_list = list()
# List with initial values
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True, None]
# List from range
numbers = list(range(10)) # [0, 1, 2, ..., 9]
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Accessing Elements
PYTHON
fruits = ['apple', 'banana', 'cherry', 'date']
# Indexing
first = fruits[0] # 'apple'
last = fruits[-1] # 'date'
# Slicing
subset = fruits[1:3] # ['banana', 'cherry']
first_two = fruits[:2] # ['apple', 'banana']
last_two = fruits[-2:] # ['cherry', 'date']
copy = fruits[:] # Full copy
# Step slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = numbers[::2] # [0, 2, 4, 6, 8]
reversed = numbers[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Modifying Lists
Adding Elements
PYTHON
fruits = ['apple', 'banana']
# Append to end
fruits.append('cherry') # ['apple', 'banana', 'cherry']
# Insert at specific position
fruits.insert(1, 'orange') # ['apple', 'orange', 'banana', 'cherry']
# Extend with multiple elements
fruits.extend(['grape', 'kiwi'])
# or
fruits += ['mango', 'peach']
Removing Elements
PYTHON
fruits = ['apple', 'banana', 'cherry', 'date', 'banana']
# Remove by value (first occurrence)
fruits.remove('banana') # ['apple', 'cherry', 'date', 'banana']
# Remove by index
del fruits[0] # ['cherry', 'date', 'banana']
# Pop (remove and return)
last = fruits.pop() # Returns 'banana'
first = fruits.pop(0) # Returns 'cherry'
# Clear all elements
fruits.clear()
Modifying Elements
PYTHON
numbers = [1, 2, 3, 4, 5]
# Single element
numbers[0] = 10 # [10, 2, 3, 4, 5]
# Multiple elements with slicing
numbers[1:3] = [20, 30] # [10, 20, 30, 4, 5]
# Replace with different length
numbers[2:4] = [100, 200, 300] # [10, 20, 100, 200, 300, 5]
List Methods
PYTHON
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Sorting
numbers.sort() # Sorts in-place
sorted_nums = sorted(numbers) # Returns new sorted list
# Reverse
numbers.reverse() # Reverses in-place
reversed_nums = numbers[::-1] # Returns new reversed list
# Count occurrences
count = numbers.count(1) # 2
# Find index
index = numbers.index(4) # Returns index of first occurrence
# Copy
nums_copy = numbers.copy()
nums_copy = numbers[:]
nums_copy = list(numbers)
List Comprehensions
PYTHON
# Basic comprehension
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Multiple conditions
filtered = [x for x in range(100) if x % 2 == 0 if x % 3 == 0]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# With conditional expression
result = [x if x > 0 else 0 for x in [-1, 2, -3, 4]]
Common Operations
Iteration
PYTHON
fruits = ['apple', 'banana', 'cherry']
# Simple iteration
for fruit in fruits:
print(fruit)
# With index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# With zip
prices = [1.5, 0.5, 2.0]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ${price}")
Searching and Filtering
PYTHON
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Check membership
if 5 in numbers:
print("Found")
# Filter with comprehension
evens = [n for n in numbers if n % 2 == 0]
# Filter with filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Find first match
first_even = next((n for n in numbers if n % 2 == 0), None)
Aggregation
PYTHON
numbers = [1, 2, 3, 4, 5]
# Built-in functions
total = sum(numbers) # 15
maximum = max(numbers) # 5
minimum = min(numbers) # 1
length = len(numbers) # 5
# Using reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers) # 120
Advanced Features
List Unpacking
PYTHON
# Basic unpacking
first, second, third = [1, 2, 3]
# With rest operator
first, *rest = [1, 2, 3, 4, 5] # first=1, rest=[2, 3, 4, 5]
first, *middle, last = [1, 2, 3, 4, 5] # first=1, middle=[2, 3, 4], last=5
# In function calls
numbers = [1, 2, 3]
print(*numbers) # Same as print(1, 2, 3)
List as Stack
PYTHON
stack = []
stack.append(1) # Push
stack.append(2)
top = stack.pop() # Pop
List as Queue (not efficient)
PYTHON
from collections import deque
# Better to use deque for queue operations
queue = deque([1, 2, 3])
queue.append(4) # Add to right
queue.popleft() # Remove from left
Performance Characteristics
- Access by index: O(1)
- Append: O(1) amortized
- Insert at beginning: O(n)
- Insert at middle: O(n)
- Remove by value: O(n)
- Pop from end: O(1)
- Pop from beginning: O(n)
- Search: O(n)
- Copy: O(n)
Best Practices
1. Use list comprehensions for simple transformations
2. Prefer append() over + for single elements
3. Use extend() or += for multiple elements
4. Be careful with mutable default arguments
5. Consider using deque for queue operations
6. Use slicing for copying lists
7. Avoid modifying lists while iterating
Common Use Cases
- Storing ordered collections
- Implementing stacks
- Temporary data storage
- Function return values
- Data processing pipelines
- Matrix operations