Python Lists & List Comprehensions
Python lists are one of the most versatile and frequently used built-in data structures in Python. They are ordered, mutable (changeable), and can store items of mixed data types. List comprehensions provide a concise, readable, and highly optimized way to create new lists based on existing iterables.
1. Python Lists Fundamentals
A list is created by placing comma-separated values inside square brackets [].
# Creating a list with mixed data types
my_list = [10, "Python", 3.14, True, [1, 2]]
# Indexing (0-based) and Slicing
print(my_list[0]) # Output: 10
print(my_list[1:3]) # Output: ['Python', 3.14] (end index is exclusive)
print(my_list[-1]) # Output: [1, 2] (negative index counts from the end)
Key List Characteristics:
- Ordered: Items maintain their defined order.
- Mutable: You can add, remove, or modify items after creation.
- Dynamic: Lists automatically resize when items are added or removed.
- Allow Duplicates: Lists can contain identical elements.
2. Essential List Operations & Methods
Python provides several built-in methods to manipulate lists efficiently:
| Method / Operation | Description | Example |
|---|---|---|
append(item) |
Adds an item to the end of the list | nums.append(4) |
insert(index, item) |
Inserts an item at a specific index | nums.insert(1, 99) |
remove(item) |
Removes the first occurrence of an item | nums.remove(99) |
pop(index) |
Removes and returns item at index (default last) | last = nums.pop() |
sort() / sorted() |
Sorts the list (in-place vs. new list) | nums.sort(reverse=True) |
len(list) |
Returns the number of items | length = len(nums) |
3. Mastering List Comprehensions
Instead of using a traditional for loop and .append() to build a list, a list comprehension condenses the operation into a single readable line.
Syntax:
new_list = [expression for item in iterable if condition]
Traditional Loop vs. List Comprehension:
Traditional Approach:
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
List Comprehension Approach:
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
4. Advanced List Comprehensions
Filtering with if Conditions
You can filter elements by adding an if clause at the end of the comprehension:
# Get only even numbers from 1 to 10
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # Output: [2, 4, 6, 8, 10]
Conditional Expressions (If-Else)
If you need to transform values conditionally before adding them, place the condition before the for clause:
# Label numbers as 'Even' or 'Odd'
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)]
print(labels) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
Nested List Comprehensions
You can flatten matrices or generate combinations using multiple for loops:
# Flatten a 2D matrix into a 1D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]