Comprehension:-
List Comprehension
• Definition: A concise way to create lists by applying an expression to each item in an iterable, optionally filtering elements.
• Syntax:
[expression for item in iterable if condition][expression for item in iterable if condition]
• Creates a new list by transforming items in an existing iterable based on the expression.
• Advantages: More readable and efficient than using traditional for-loops.
• Basic Example: Square numbers in a list
python
numbers = [1, 2, 3, 4]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16]
• With Condition: Only include even numbers
1. Start
2. Given a list named numbers.
3. Create an empty list called evens.
4. For each element in numbers:
• If the element is divisible by 2 (i.e., element % 2 == 0):
• Add the element to evens.
5. Print the list evens.
6. End
• With if-else: Label numbers as even or odd
1. Start
2. Given a list named numbers.
3. Create an empty list called labels.
4. For each element in numbers:
a. If the element is divisible by 2 (element % 2 == 0):
i. Add the string "Even" to labels
b. Else:
i. Add the string "Odd" to labels
5. Print the list labels
6. End
Dictionary Comprehension
• Definition: Similar to list comprehension but used to create dictionaries.
• Syntax:
{key_expression:value_expression for item in iterable if condition}
• Creates a new dictionary by generating keys and values from an iterable.
• Basic Example: Square numbers as values with numbers as keys
python
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
• With Condition: Include only even numbers as keys
• Start
• Create an empty dictionary called even_squares
• For each number x in the range 0 to 9:
• If x is divisible by 2 (i.e., x % 2 == 0):
• Add an entry to even_squares with key = x and value = x squared (x**2)
• Print the dictionary even_squares
• End
Key Points
• Both comprehensions are syntactic sugar for loops and conditionals, making code more compact and readable.
• Use comprehensions for simple transformations and filtering in one line.
• For complex logic, traditional loops with explicit statements might be preferred for clarity.
• Comprehensions maintain the original data unchanged and produce new collections.
Top comments (0)