List Comprehensions: The Python Magic Spell! ✨

Create lists in just one line of code! It's like telling Python exactly what you want in your shopping basket! 🛒

What Are List Comprehensions?
A superpower for creating lists!

List comprehensions are a shortcut way to create lists in Python. They let you create a new list by transforming or filtering elements from another list (or any iterable) in a single line of code!

Basic syntax: [expression for item in iterable (if condition)]

Why use List Comprehensions?

🚀 Faster Code

They're usually quicker than regular loops!

✨ Cleaner Code

One line instead of 3-4 lines!

🧠 Easier to Read

Once you get used to them!

The Magic Visualization
squares = []for x in range(5):squares.append(x**2)squares = [x**2 for x in range(5)][0, 1, 4, 9, 16]

One line does the work of many! ✨

Try It Yourself! 🧪
Experiment with list comprehensions

Your Code:

Output:

[0, 1, 4, 9, 16]

Advanced List Comprehension Tricks! 🧙‍♂️

Nested List Comprehensions
List-ception! A list within a list!

table = [[x * y for x in range(1, 6)] for y in range(1, 6)]

1
2
3
4
5
2
4
6
8
10
3
6
9
12
15
4
8
12
16
20
5
10
15
20
25

This creates a 5×5 multiplication table with just one line of code!

Flattening a Nested List:

nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]

[1, 2, 3, 4, 5, 6]

This takes a list of lists and "flattens" it into a single list!

Fun Advanced Examples
Cool things you can do!

Removing Vowels:

word = "Tesla"
without_vowels = [ch for ch in word if ch.lower() not in "aeiou"]

['T', 's', 'l']

Like removing all the vowels from your secret code message! 🕵️

Color-Size Combinations:

colors = ["red", "blue"]
sizes = ["small", "medium"]
combinations = [(color, size) for color in colors for size in sizes]

(red, small)
(red, medium)
(blue, small)
(blue, medium)

Like creating all possible t-shirt combinations in your store! 👕

Cheat Sheet! 📝

Basic List Comprehension

[expression for item in iterable]

Creates a new list by applying the expression to each item

With Condition

[expression for item in iterable if condition]

Only includes items that meet the condition

Nested List Comprehension

[expression for item1 in iterable1 for item2 in iterable2]

Loops through two iterables (like nested for loops)

Creating Nested Lists

[[expression for item1 in iterable1] for item2 in iterable2]

Creates a list of lists (like a 2D array)