Tuesday, August 26, 2025

🐍COMPREHENSIONS IN PYTHON

Comprehensions provide a concise way to create lists, dictionaries, and sets using a single line of code.

1) What are Comprehensions?

Comprehensions allow you to generate new collections (lists, dictionaries, or sets) from existing iterables in a single line. They are more readable and often faster than using loops.

2) List Comprehensions

Basic syntax:


new_list = [expression for item in iterable if condition]

Example:


# Squares of numbers 1-5
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# Even numbers only
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

3) Set Comprehensions

Similar to list comprehensions but produce a set (unique, unordered elements):


numbers = [1, 2, 2, 3, 3, 4]
unique_squares = {x**2 for x in numbers}
print(unique_squares)  # {1, 4, 9, 16}

4) Dictionary Comprehensions

Create dictionaries from iterables:


# Number squares as key-value pairs
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)  
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filtering
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

5) Nested Comprehensions

Comprehensions can also contain nested loops:


# Flatten a 2D list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6]

6) Common Mistakes

  • Forgetting the brackets/curly braces → x for x in range(5) ❌
  • Using assignment (=) instead of expression (: in dict comprehension)
  • Overcomplicating nested comprehensions → reduce readability

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??