Practical – 154 : Construct and analyze code segments that include List comprehensions, tuple ,set and dictionary comprehensions
Certainly! Let’s break this down into constructing and analyzing Python code segments that use:
- ✅ List Comprehension
- ✅ Tuple Comprehension (via generator)
- ✅ Set Comprehension
- ✅ Dictionary Comprehension
Each comprehension is a compact way to create collections with a single readable expression.
✅ 1. List Comprehension
🔹 Example:
squares = [x**2 for x in range(1, 6)]
print(“Squares List:”, squares)
🔍 Analysis:
- Creates a list of squares from 1 to 5.
- Equivalent to:
- squares = []
- for x in range(1, 6):
- squares.append(x**2)
✅ 2. Tuple Comprehension (Using Generator Expression)
Python does not have direct tuple comprehension, but generator expressions inside tuple() simulate it.
🔹 Example:
squares_tuple = tuple(x**2 for x in range(1, 6))
print(“Squares Tuple:”, squares_tuple)
🔍 Analysis:
- Generator expression passed to tuple() converts output into a tuple.
- Memory-efficient for large sequences.
✅ 3. Set Comprehension
🔹 Example:
unique_squares = {x**2 for x in [1, 2, 2, 3, 3, 4]}
print(“Unique Squares Set:”, unique_squares)
🔍 Analysis:
- Duplicates are automatically removed.
- Results in {1, 4, 9, 16}.
✅ 4. Dictionary Comprehension
🔹 Example:
square_dict = {x: x**2 for x in range(1, 6)}
print(“Square Dictionary:”, square_dict)
🔍 Analysis:
- Keys are numbers 1 to 5, values are their squares.
- Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
✅ Bonus: Conditional Comprehensions
🔹 List with if condition:
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(“Even Squares:”, even_squares)
🔹 Dictionary with condition:
even_dict = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(“Even Square Dict:”, even_dict)
🔚 Summary Table:
|
Type |
Syntax Example |
Use Case |
|
List |
[x for x in range(5)] |
Create or filter list |
|
Tuple |
tuple(x for x in range(5)) |
Memory-efficient tuples |
|
Set |
{x for x in [1,2,2,3]} |
Unique values automatically |
|
Dictionary |
{x: x**2 for x in range(5)} |
Key-value mappings |