Python Data Structures Series

Python Lists
Complete Mastery Guide

Everything you need to know about Python lists - from basic operations to advanced techniques, performance considerations, and practical assignments.

📋

Lists in Python

Most Used Data Structure

Flexibility ⭐⭐⭐⭐⭐
Performance ⭐⭐⭐⭐
Learning Curve ⭐⭐⭐
1

What is a Python List?

Ordered & Mutable Collection

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.

list_examples.py
# 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
2

Creating Lists in Python

Multiple Initialization Methods

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)
3

Complete List Methods Reference

15 Essential Methods
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)
4

Advanced List Comprehensions

Pythonic One-Liners

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}
5

Performance & Best Practices

Time Complexity & Optimization

Time Complexity Guide

Indexing/Access O(1)

Constant time: lst[0], lst[-1]

Appending/Extending O(1)*

*Amortized constant time

Insertion/Deletion at beginning O(n)

All elements must shift

Search (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")
6

List vs Tuple: When to Use Which?

Comparative Analysis
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
7

Practical List Assignments

Hands-On Practice Problems

Test your understanding with these practical exercises. Try to solve them without looking at solutions first!

Beginner 15 min

1. Basic Operations

Create a list of 10 numbers. Find the sum, average, maximum, and minimum without using built-in functions.

Try Solution Expected: 4 functions
Intermediate 25 min

2. List Manipulation

Given two lists, merge them, remove duplicates, and sort in descending order using only list methods.

Try Solution Expected: 5 steps
Intermediate 20 min

3. List Comprehension

Generate a list of prime numbers between 1-100 using list comprehension with a helper function.

Try Solution Expected: 25 primes
Advanced 30 min

4. Matrix Operations

Implement matrix addition and multiplication using nested lists. Handle different dimensions.

Try Solution Expected: 2 functions
Advanced 40 min

5. Performance Challenge

Compare three methods for removing duplicates from a list of 1 million integers. Measure execution time.

Try Solution Expected: timeit results
Project 60 min

6. To-Do List Manager

Build a command-line to-do list with add, remove, mark complete, list, and priority features.

Try Solution Expected: 5 features
8

Additional Resources & References

Official Docs & Learning Materials