⚡ Python Tutorial — List Comprehensions

Introduction 🌟

List Comprehensions provide a concise, elegant, and fast way to create lists in Python. Instead of writing long loops, you can build lists using a compact expression.

Note

💡 Faster than traditional loops
💡 More readable and Pythonic
💡 Supports conditions, nested loops, transformations

1. Basic Syntax 🧱

basic_syntax.py

new_list = [expression for item in iterable]

✔ expression → what to store
✔ item → each element
✔ iterable → list, tuple, string, range, etc.

2. Simple Example 🎯

simple_example.py

nums = [1, 2, 3, 4]
squares = [n * n for n in nums]
print(squares)  # [1, 4, 9, 16]

✔ Equivalent to writing a loop, but cleaner

3. With Condition (Filtering) 🔍

filter_example.py

nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)

✔ Only includes values passing the condition

4. Transform + Filter Together 🧠

transform_filter.py

nums = [1,2,3,4,5]
doubles_of_even = [n * 2 for n in nums if n % 2 == 0]
print(doubles_of_even)  # [4, 8]

5. Nested Loops in List Comprehension 🔁

nested_loops.py

pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)

✔ Equivalent to two nested loops

6. List Comprehension with Strings 🔡

string_example.py

word = "Python"
letters = [char.upper() for char in word]
print(letters)

7. Using Conditional Expression (if–else) ⚖️

if_else_example.py

nums = [1,2,3,4,5]
output = ["even" if n % 2 == 0 else "odd" for n in nums]
print(output)

Note

⚠️ `if–else` goes **before** the loop in list comprehensions
✔ Filtering condition goes **after** the loop

8. Flattening Nested Lists 📥

flatten_list.py

nested = [[1,2], [3,4,5]]
flat = [num for sub in nested for num in sub]
print(flat)

✔ Clean way to flatten lists

9. Using Functions inside Comprehensions 🛠️

function_usage.py

def square(n):
    return n * n

nums = [1, 2, 3]
result = [square(n) for n in nums]
print(result)

10. Complex Comprehension Example 🎨

complex_example.py

nums = range(10)
result = [n**2 for n in nums if n % 3 == 0]
print(result)  # squares of multiples of 3

11. Real-World Example — Extracting Emails 📧

email_example.py

users = [
    {"name": "A", "email": "a@mail.com"},
    {"name": "B", "email": "b@mail.com"},
]

emails = [u["email"] for u in users]
print(emails)

12. Real-World Example — Filter Valid Values ✔️❌

clean_data.py

raw = ["10", "20", "abc", "30"]
clean = [int(x) for x in raw if x.isdigit()]
print(clean)  # [10, 20, 30]

13. Nested List Comprehension — Multiplication Table 🔢

multiplication_table.py

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

14. List Comprehension vs Traditional Loop ⚡

Traditional LoopList Comprehension
result = [] for n in nums: result.append(n*n)[n*n for n in nums]

✔ Comprehensions are shorter
✔ Usually faster

15. List Comprehension with Multiple Conditions 🧩

multi_condition.py

nums = range(20)
filtered = [n for n in nums if n % 2 == 0 if n > 10]
print(filtered)  # even numbers > 10

16. Avoid Overly Complex Comprehensions ⚠️

Note

⚠️ If your comprehension becomes too long or unreadable, use normal loops for clarity.

List Comprehension Cheat Sheet 📘

PatternExample
Basic[x for x in iterable]
Transform[x*2 for x in nums]
Filter[x for x in nums if x>5]
If–Else["yes" if c else "no" for c in cond]
Nested Loops[(x,y) for x in a for y in b]
Flatten[n for sub in lst for n in sub]

Best Practices 💡

  • ✔ Keep comprehensions readable and simple
  • ✔ Use comprehensions for transformation or filtering
  • ✔ Avoid nesting more than 2 loops
  • ✔ Prefer functions for complex logic

Conclusion 🎉

>>“List comprehensions make Python expressive — turning loops into elegant, powerful one-liners.” ✨

You now fully understand List Comprehensions in Python! Want the next topic? Try Dictionary Comprehensions, Generators, Lambda Functions, or Decorators. Just tell me! 😊

🔑 Python Tutorial — Dictionary Comprehensions

Introduction 🌟

Dictionary Comprehensions offer a clean, fast, and expressive way to create dictionaries using a single compact expression. They work similarly to list comprehensions, but produce key–value pairs.

Note

💡 More readable than loops
💡 Faster and more Pythonic
💡 Supports conditions, transformations, nested loops

1. Basic Syntax 🧱

basic_syntax.py

new_dict = {key_expr: value_expr for item in iterable}

✔ key_expr → expression for dictionary key
✔ value_expr → expression for dictionary value
✔ iterable → list, tuple, dict, string, range, etc.

2. Simple Example 🎯

simple_example.py

nums = [1, 2, 3, 4]
squares = {n: n*n for n in nums}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16}

✔ Creates a key-value mapping in one line

3. Using Conditions (Filtering) 🔍

filter_example.py

nums = [1, 2, 3, 4, 5, 6]
even_squares = {n: n*n for n in nums if n % 2 == 0}
print(even_squares)

✔ Only includes items that pass the condition

4. Transforming Keys & Values 🧠

transform_example.py

words = ["apple", "banana", "cherry"]
lengths = {word: len(word) for word in words}
print(lengths)

✔ Useful for mapping real-world data

5. Using if–else in Dict Comprehension ⚖️

if_else_example.py

nums = [1, 2, 3, 4, 5]
parity = {n: ("even" if n % 2 == 0 else "odd") for n in nums}
print(parity)

Note

💡 When using if–else, it goes in the **value expression**, not after the loop.

6. Creating Dictionaries from Existing Dictionaries 🔁

dict_comprehension_from_dict.py

prices = {"apple": 100, "banana": 40, "orange": 60}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)

7. Swapping Keys and Values 🔄

swap_keys_values.py

data = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in data.items()}
print(swapped)

✔ Simple and powerful reversal technique

8. Nested Loops in Dict Comprehension 🔁

nested_loop_example.py

pairs = {(x, y): x + y for x in range(2) for y in range(2)}
print(pairs)

✔ Equivalent to two nested loops generating dictionary keys

9. Dictionary Comprehensions with Strings 🔡

string_dict_example.py

word = "hello"
freq = {char: word.count(char) for char in word}
print(freq)

✔ Useful for character counting

10. Real-World Example — Removing Invalid Data ✔️❌

clean_data.py

raw = {"a": "10", "b": "abc", "c": "30"}
clean = {k: int(v) for k, v in raw.items() if v.isdigit()}
print(clean)

11. Real-World Example — Converting Temperature 🌡️

temp_conversion.py

temps_c = {"Mumbai": 32, "Delhi": 38, "Chennai": 35}
temps_f = {city: (temp * 9/5) + 32 for city, temp in temps_c.items()}
print(temps_f)

12. Real-World Example — Index Mapping Generator 🔢

index_map.py

items = ["apple", "banana", "cherry"]
index_map = {item: i for i, item in enumerate(items)}
print(index_map)

13. Dict Comprehension vs Traditional Loop ⚡

Traditional LoopDict Comprehension
result = {} for n in nums: result[n] = n*n{n: n*n for n in nums}

✔ Cleaner
✔ Faster
✔ More expressive

14. Multiple Conditions in Dict Comprehension 🧩

multi_condition.py

nums = range(20)
filtered = {n: n*n for n in nums if n % 2 == 0 if n > 10}
print(filtered)

15. Avoid Overly Complex Comprehensions ⚠️

Note

⚠️ If your comprehension becomes long or confusing, prefer normal loops for readability.

Dictionary Comprehension Cheat Sheet 📘

PatternExample
Basic{x: f(x) for x in iterable}
Filter{k: v for k,v in data if cond}
If–Else{x: "yes" if cond else "no" for x in arr}
Swap{v: k for k,v in data.items()}
Nested Loops{(x,y): ... for x in a for y in b}

Best Practices 💡

  • ✔ Use dict comprehensions for mapping, transforming, filtering
  • ✔ Keep expressions readable
  • ✔ Avoid nesting more than 2 loops
  • ✔ Great for data cleaning and restructuring

Conclusion 🎉

>>“Dictionary comprehensions turn complex mapping logic into elegant, readable, and efficient expressions.” ✨

You now fully understand Dict Comprehensions in Python! Want the next topic? Try Set Comprehensions, Generators, Decorators, or Lambda Functions. Just tell me! 😊

🧩 Python Tutorial — Set Comprehensions

Introduction 🌟

Set Comprehensions provide a clean, compact, and efficient way to create sets in Python. They work similarly to list and dictionary comprehensions but generate a set of **unique** items.

Note

💡 Sets automatically remove duplicates
💡 Faster than manually adding elements in a loop
💡 Perfect for filtering, deduplication, and transformations

1. Basic Syntax 🧱

basic_syntax.py

new_set = {expression for item in iterable}

✔ Always uses
✔ Creates a set → unordered & unique items

2. Simple Example 🎯

simple_example.py

nums = [1, 2, 2, 3, 4, 4]
unique_nums = {n for n in nums}
print(unique_nums)  # {1, 2, 3, 4}

✔ Automatically removes duplicates

3. Transforming Elements 🧠

transform_example.py

nums = [1, 2, 3, 4]
squares = {n*n for n in nums}
print(squares)

✔ Good for math operations or data restructuring

4. Filtering with Conditions 🔍

filter_example.py

nums = range(10)
evens = {n for n in nums if n % 2 == 0}
print(evens)  # {0, 2, 4, 6, 8}

✔ Only includes even numbers

5. If–Else in Set Comprehension ⚖️

if_else_example.py

nums = [1, 2, 3]
labels = {"even" if n % 2 == 0 else "odd" for n in nums}
print(labels)  # {'even', 'odd'}

Note

💡 When using if–else, it must be inside the expression, not after the loop.

6. Creating Sets from Strings 🔡

string_example.py

letters = {char for char in "programming"}
print(letters)

✔ Removes repeated characters automatically

7. Nested Loops in Set Comprehension 🔁

nested_loops.py

pairs = {(x, y) for x in range(2) for y in range(3)}
print(pairs)

✔ Generates all (x, y) combinations

8. Real-World Example — Extract Unique Words 📚

unique_words.py

sentence = "python is fun and python is powerful"
unique_words = {word for word in sentence.split()}
print(unique_words)

9. Real-World Example — Filter Valid Data ✔️❌

clean_data.py

raw = ["10", "20", "abc", "30", "abc"]
valid = {int(x) for x in raw if x.isdigit()}
print(valid)  # {10, 20, 30}

10. Real-World Example — Unique Domain Extractor 🌍

domain_example.py

emails = ["a@mail.com", "b@gmail.com", "c@mail.com"]
domains = {email.split("@")[1] for email in emails}
print(domains)

✔ Useful for analytics and grouping tasks

11. Real-World Example — Unique Character Frequencies 🧮

char_freq.py

text = "banana"
freqs = {(char, text.count(char)) for char in text}
print(freqs)

12. Set Comprehension vs Traditional Loop ⚡

Traditional LoopSet Comprehension
result = set() for n in nums: result.add(n*n){n*n for n in nums}

✔ Shorter
✔ Faster
✔ More declarative

13. Multiple Conditions 🧩

multi_condition.py

nums = range(20)
filtered = {n for n in nums if n % 2 == 0 if n > 10}
print(filtered)  # {12, 14, 16, 18}

14. Avoid Complex Nested Comprehensions ⚠️

Note

⚠️ Deeply nested comprehensions can hurt readability. Use loops when logic becomes too complex.

Set Comprehension Cheat Sheet 📘

PatternExample
Basic{x for x in iterable}
Transform{x*2 for x in nums}
Filter{x for x in nums if x>5}
If–Else{"even" if n%2==0 else "odd" for n in nums}
Nested Loops{(x,y) for x in a for y in b}
Strings{char for char in text}

Best Practices 💡

  • ✔ Use set comprehensions for deduplication tasks
  • ✔ Keep expressions simple and readable
  • ✔ Combine with string operations for parsing
  • ✔ Use filtering to clean raw data

Conclusion 🎉

>>“Set comprehensions offer a fast, readable, and Pythonic way to generate unique collections with powerful logic.” ✨

You now fully understand Set Comprehensions in Python! Want the next topic? Try Generators, Decorators, Iterable Protocol, or Lambda Functions. Just tell me! 😊