Array Methods vs Comprehensions
Transforming and filtering data collections
Introduction
In this lesson, you'll learn about array methods vs comprehensions in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with transforming and filtering data collections.
Python has its own approach to transforming and filtering data collections, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
nums = [1, 2, 3, 4, 5, 6]
# List comprehension – map
doubled = [n * 2 for n in nums]
# List comprehension – filter
evens = [n for n in nums if n % 2 == 0]
# sum() – built-in reduce for addition
total = sum(nums)
# Chaining (filter + map in one)
result = [n**2 for n in nums if n % 2 == 0]
# next() with generator – find
first = next((n for n in nums if n > 3), None)
# all() / any()
all_pos = all(n > 0 for n in nums)
any_big = any(n > 5 for n in nums)Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
const nums = [1, 2, 3, 4, 5, 6];
// map – transform
const doubled = nums.map(n => n * 2);
// filter – select
const evens = nums.filter(n => n % 2 === 0);
// reduce – aggregate
const sum = nums.reduce((acc, n) => acc + n, 0);
// chaining
const result = nums
.filter(n => n % 2 === 0)
.map(n => n ** 2);
// find / findIndex
const first = nums.find(n => n > 3);
const idx = nums.findIndex(n => n > 3);
// every / some
const allPos = nums.every(n => n > 0);
const anyBig = nums.some(n => n > 5);You may be used to different syntax or behavior.
[expr for x in lst if cond] replaces map+filter
You may be used to different syntax or behavior.
sum(), min(), max() are built-in
You may be used to different syntax or behavior.
next(gen, default) ≈ find()
You may be used to different syntax or behavior.
all() / any() ≈ every() / some()
Step-by-Step Breakdown
1. Map with List Comprehension
Place the transformation expression first, then the for clause.
const doubled = nums.map(n => n * 2);doubled = [n * 2 for n in nums]2. Filter with List Comprehension
Add an if clause at the end to filter.
const evens = nums.filter(n => n % 2 === 0);evens = [n for n in nums if n % 2 == 0]3. Dict & Set Comprehensions
Python supports dict and set comprehensions too.
const obj = Object.fromEntries(pairs.map(([k,v]) => [k, v*2]));d = {k: v*2 for k, v in pairs}
s = {n**2 for n in nums} # set comprehensionCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- [expr for x in lst if cond] replaces map+filter
- sum(), min(), max() are built-in
- next(gen, default) ≈ find()
Key Takeaways
- [expr for x in lst if cond] — Pythonic one-liner
- sum/min/max built-in for common reductions
- Dict {} and set {} comprehensions also available