January 30, 2026 · All About CS
Python List Comprehension and Slicing
Write cleaner Python with list comprehensions and slicing — learn concise syntax for filtering, transforming, and extracting data from lists.
Python List Comprehension and Slicing
Two features elevate Python lists from "useful" to "elegant": list comprehensions and slicing. Comprehensions let you build new lists in a single expressive line, while slicing gives you surgical control over subsequences — no loops required. Together, they form the backbone of idiomatic Python.
Key Takeaways
- List comprehensions replace multi-line loops with a concise
[expression for item in iterable]syntax. - Conditions can filter items (
ifafter the loop) or branch the expression (if/elsebefore the loop). - Slicing uses
list[start:stop:step]to extract sub-lists without mutating the original. - Negative indices and the step parameter unlock powerful patterns like reversal in one expression.
- Comprehensions and slicing combine beautifully with built-in functions like
sum()andlen().
List Comprehension
Traditional Loop vs Comprehension
Suppose you want only the even values from a list. The traditional approach works but is verbose:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens) # [2, 4, 6, 8, 10]A list comprehension compresses this into a single line. The general syntax is [expression for item in iterable if condition]:
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]🖼️ Visual Suggestion: Annotated diagram mapping each part of
[n for n in numbers if n % 2 == 0]to its role: expression, loop variable, iterable, filter condition.
Transforming Elements
Comprehensions are not limited to filtering — the expression can transform each item. A common example is squaring every number:
nums = [1, 2, 3, 4, 5]
squared = [n ** 2 for n in nums]
print(squared) # [1, 4, 9, 16, 25]Filtering with a Condition (After the Loop)
When the if clause appears after the for, it acts as a gate — only items that pass make it into the new list.
words = ["apple", "bat", "cherry", "dog", "elderberry"]
long_words = [w for w in words if len(w) > 3]
print(long_words) # ["apple", "cherry", "elderberry"]Conditional Expression (Before the Loop)
When you need an if/else to choose between two expressions — rather than to filter — the conditional goes before the for keyword.
nums = [1, 2, 3, 4, 5, 6]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels) # ["odd", "even", "odd", "even", "odd", "even"]Every element produces a result here — the if/else decides which expression to use, not whether to include the item.
raw_inputs = [" Alice ", "BOB", " charlie", " Dave "]
clean = [name.strip().title() for name in raw_inputs]
print(clean) # ["Alice", "Bob", "Charlie", "Dave"]Comprehension Key Points
- Use a post-loop
ifwhen you want to exclude items. - Use a pre-loop
if/elsewhen you want to transform items conditionally. - Keep comprehensions readable — if the logic spans more than ~80 characters, consider a regular loop.
List Slicing
Slicing extracts a portion of a list using the syntax list[start:stop:step]. The original list is never modified — a new list is returned.
Basic Slicing: list[m:n]
The slice includes index m (inclusive) up to but not including index n (exclusive).
letters = ["a", "b", "c", "d", "e", "f"]
print(letters[1:4]) # ["b", "c", "d"]
print(letters[0:2]) # ["a", "b"]🖼️ Visual Suggestion: A list with fence-post markers between elements, showing that slice boundaries fall between items — making the exclusive upper bound intuitive.
Omitting Indices and Negative Indexing
Leave out start to begin from 0, or stop to go through the end. Negative indices count backward.
print(letters[:3]) # ["a", "b", "c"] — first three
print(letters[3:]) # ["d", "e", "f"] — index 3 onward
print(letters[-3:]) # ["d", "e", "f"] — last three
print(letters[-4:-1]) # ["c", "d", "e"] — negative rangeThe Step Parameter
The third value in the slice controls the step — how many positions to advance between selected elements.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[::2]) # [0, 2, 4, 6, 8] — every second element
print(nums[1::2]) # [1, 3, 5, 7, 9] — odd-indexed elements
print(nums[::3]) # [0, 3, 6, 9] — every third elementReversing a List with [::-1]
A step of -1 traverses the list backward, producing a reversed copy.
greeting = ["H", "e", "l", "l", "o"]
print(greeting[::-1]) # ["o", "l", "l", "e", "H"]This idiom is one of the most recognized Python one-liners.
Combining Slicing with Built-in Functions
Because slices return regular lists, you can feed them directly into functions like sum(), min(), max(), and len().
scores = [70, 85, 90, 60, 95, 88, 76, 92]
print(sum(scores[4:])) # 351 — sum of last four
print(sum(scores[2:6])) # 333 — sum of a middle window
print(max(scores[:4])) # 90 — max of first fourQuick Reference Table
| Expression | Result | Description |
|---|---|---|
lst[2:5] | Items at index 2, 3, 4 | Basic slice |
lst[:3] | First 3 items | Omit start |
lst[3:] | Index 3 to end | Omit stop |
lst[:] | Full shallow copy | Omit both |
lst[::2] | Every 2nd item | Step of 2 |
lst[::-1] | Reversed list | Negative step |
lst[-3:] | Last 3 items | Negative start |
Comprehension + Slicing: Better Together
The real power emerges when you combine both techniques:
data = [12, 45, 7, 23, 56, 89, 34, 67, 2, 91]
result = [x ** 2 for x in data[:5] if x > 10]
print(result) # [144, 2025, 529]
temps = [22, 25, 19, 30, 28, 17, 24]
weekday_avg = sum(temps[:5]) / len(temps[:5])
print(f"Weekday avg: {weekday_avg:.1f}°") # 24.8°Mastering comprehensions and slicing is a milestone in your Python journey. They reduce boilerplate, clarify intent, and unlock a more expressive coding style.
Up next: we explore tuples and dictionaries — Python's other essential built-in data structures.