Week 15 - Python Extras
Advanced Python Features¶
Learning Objectives¶
- Understand and apply Python sets for unique data manipulation and operations.
- Explore
collections.Counter
for counting elements and performing multiset operations. - Learn to utilize
defaultdict
for simplifying dictionary initialization and handling missing keys. - Use conditional expressions for concise code and logical branching.
- Master list comprehensions for creating lists efficiently.
- Understand
any
andall
built-in functions for evaluating conditions across sequences. - Familiarize with packing and unpacking keyword arguments for flexible function calls.
1. Python Sets¶
Objective: Demonstrate set creation, operations, and practical applications.
Examples:
1. Creating and Manipulating Sets
1 2 |
|
-
Set Operations
1 2 3 4 5 6 7
evens = {2, 4, 6, 8} odds = {1, 3, 5, 7} primes = {2, 3, 5, 7} print(evens | odds) # Union print(primes & evens) # Intersection print(odds - primes) # Difference print(odds <= primes) # Subset
-
Practical Example
Check if two lists share common elements:
1 2 3
list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] print(bool(set(list1) & set(list2))) # True
2. Using collections.Counter
¶
Objective: Count elements in sequences and perform arithmetic operations.
Examples:
1. Counting Elements
1 2 3 4 |
|
-
Arithmetic Operations
1 2 3 4
counter1 = Counter({'a': 3, 'b': 2}) counter2 = Counter({'b': 1, 'c': 4}) print(counter1 + counter2) # Counter({'c': 4, 'a': 3, 'b': 3}) print(counter1 - counter2) # Counter({'a': 3, 'b': 1})
-
Anagram Checker
1 2 3
def are_anagrams(word1, word2): return Counter(word1) == Counter(word2) print(are_anagrams('listen', 'silent')) # True
3. collections.defaultdict
¶
Objective: Simplify dictionary initialization for dynamic values.
Examples:
1. Basic Usage
1 2 3 4 |
|
- Grouped Data
1 2 3 4 5
names = [('USA', 'Alice'), ('USA', 'Bob'), ('India', 'Ravi')] grouped = defaultdict(list) for country, name in names: grouped[country].append(name) print(grouped) # defaultdict(<class 'list'>, {'USA': ['Alice', 'Bob'], 'India': ['Ravi']})
4. Conditional Expressions¶
Objective: Write concise conditional logic.
Examples:
1. Inline Logic
1 2 3 |
|
- Recursive Example
1 2 3
def factorial(n): return 1 if n == 0 else n * factorial(n - 1) print(factorial(5)) # 120
5. List Comprehensions¶
Objective: Simplify list construction.
Examples:
1. Simple Transformation
1 2 3 |
|
- Filter with Comprehension
1 2 3
names = ['Alice', 'Bob', 'Charlie'] short_names = [name for name in names if len(name) <= 4] print(short_names) # ['Bob']
6. Built-ins: any
and all
¶
Objective: Use these functions for efficient sequence checks.
Examples:
1. Using any
1 2 |
|
- Using
all
1 2
values = [1, 1, 1] print(all(values)) # True
7. Packing and Unpacking Keyword Arguments¶
Objective: Pass dynamic arguments to functions.
Examples:
1. Packing Arguments
1 2 3 4 |
|
- Unpacking into Function Calls
1 2
data = {'name': 'Bob', 'age': 30} display_info(**data)
Activities¶
- Set Operations: Find common and unique elements between two lists.
- Counter Applications: Write a program to count votes and find the winner.
- Defaultdict Usage: Implement a function to group words by their first letter.
- List Comprehensions: Create a list of even numbers from 1 to 20.
any
andall
: Check if a list contains only positive numbers.