Daniel Lyons' Notes

10 Python Comprehensions You SHOULD Be Using

Description

To learn programming and Python - check out Datacamp!đź’» Learn Python - https://datacamp.pxf.io/anvmQođź’» Learn Programming - https://datacamp.pxf.io/k0D3G3In ...

Notes

00:00 Introduction to Python Comprehensions

  • Video covers 10 Python comprehensions progressing in difficulty
  • 00:10 Starting with basic list comprehension

00:12 Basic List Comprehension

  • 00:15 Traditional approach: loop through range and append to list
  • 00:33 List comprehension syntax: [x for x in range(10)]
    • Faster and more readable than traditional loops
    • Expression on left (what gets added), for loop on right
  • 01:36 Modifying the expression: [x + 1 for x in range(10)] produces values 1-10

02:06 List Comprehension with Filtering

  • 02:12 Getting even numbers: add conditional after for loop
    • Syntax: [number for number in range(50) if number % 2 == 0]
    • Multiple if statements can be chained together
  • 03:50 Natural, readable syntax makes code clearer than traditional loops

05:20 Complex Filtering with Multiple Conditions

for string in options:
    if len(string) <= 1:
        continue
    
    if string[0] != "a":
        continue
    
    if string[-1] != "y":
        continue
    
    valid_strings.append(string)

print(valid_strings)

  • Filter strings starting with 'A' and ending with 'Y'
    • Check string length >= 2
    • Verify first character equals 'A'
    • Verify last character equals 'Y'

Complex Filtering with Comprehensions

valid_strings = [
    string
    for string in options
    if len(string) >= 2
    if string[0] == "a"
    if string[-1] == "y"
]

print(valid_strings)

  • 06:28 Multi-line formatting: split long comprehensions across lines while inside brackets
  • 07:37 Result shows "Amy" and "Albany" correctly identified

07:42 Nested List Comprehension

for row in matrix:
    for num in row:
        flattened.append(num)

  • 07:47 Flattening a matrix (2D list into 1D list)
    • Syntax: [num for row in matrix for num in row]
    • First for loop is exterior, subsequent loops are interior
    • Interior loops execute for each iteration of exterior loop

With Comprehensions

flattened = [num for row in matrix for num in row]
  • 09:07 Can chain multiple for loops but becomes confusing with more than 2-3

09:19 If-Else Logic in Comprehensions

for number in range(10):
    if number % 2 == 0:
        categories.append("Even")
    else:
        categories.append("Odd")
  • 09:26 Categorizing numbers as "even" or "odd"
    • Syntax: [("even" if x % 2 == 0 else "odd") for x in range(10)]
    • Expression on left determines value to add (not for filtering)
    • Ternary operator (if-else) works on left side of comprehension
categories = [
    "Even" if x % 2 == 0 else "Odd" for x in range(10)
]

11:24 Building Multidimensional Lists

import pprint

lst = []
for a in range(5):
    l1 = []
    for b in range(5):
        l2 = []
        for num in range(5):
            l2.append(num)
        l1.append(l2)
    lst.append(l1)

print(lst)
  • 11:36 Creating 5Ă—5Ă—5 3D matrix
    • Traditional approach uses nested loops and append operations

12:31 Comprehension approach

lst = [[[num for num in range(5)] for _ in range(5)] for _ in range(5)]
  • Anonymous variable _ used when iteration variable not needed
  • 13:32 Reading nested comprehensions: find first for loop, check left side to understand what's added at each level

14:35 Functions in Comprehensions

  • Apply function to values: [square(x) for x in range(10)]
  • Function calls work on left side for transformation
  • Function calls can be used in filtering conditions too
  • Clean variable names make complex comprehensions readable

15:40 Dictionary Comprehension

pairs = [("a", 1), ("b", 2), ("c", 3)]
my_dict = {k: v for k, v in pairs}
print(my_dict)
# {'a': 1, 'b': 2, 'c': 3}
  • 15:45 Converting list of tuples to dictionary
    • Syntax: {k: v for k, v in pairs}
    • Unpacking tuple values as key and value
  • 16:39 Can apply functions or modify keys and values

16:49 Set Comprehension

nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x**2 for x in nums}
# {16, 1, 4, 9}
# REMEMBER that Python sets are non-ordered
  • 16:52 Syntax: {value for value in iterable}
    • Similar to dictionary but no key-value pairs
  • 17:21 Removing duplicates while applying transformation
    • Example: squaring values and storing unique results in set

17:49 Generator Comprehension (Advanced)

sum_of_squares = sum(x**2 for x in range(1000000))
  • 18:05 Summing squares from 0 to 1 million without storing all values
    • Generator syntax (parentheses): sum(x**2 for x in range(1000000))
    • Generates values on-demand rather than pre-generating entire list
  • 18:12 Memory efficient: only stores current value, not all 1 million values
  • 20:31 Using list brackets instead of parentheses creates list comprehension (stores all values in memory)
  • 21:14 Recommended to learn more about generators and iterators
10 Python Comprehensions You SHOULD Be Using
Interactive graph
On this page
Description
Notes
00:00 Introduction to Python Comprehensions
00:12 Basic List Comprehension
02:06 List Comprehension with Filtering
05:20 Complex Filtering with Multiple Conditions
Complex Filtering with Comprehensions
07:42 Nested List Comprehension
With Comprehensions
09:19 If-Else Logic in Comprehensions
11:24 Building Multidimensional Lists
12:31 Comprehension approach
14:35 Functions in Comprehensions
15:40 Dictionary Comprehension
16:49 Set Comprehension
17:49 Generator Comprehension (Advanced)