Skip to content

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 and all 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
fruits = set(['apple', 'orange', 'banana', 'apple'])  # Duplicates removed
print(fruits)  # {'orange', 'banana', 'apple'}

  1. 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
    

  2. 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
from collections import Counter
votes = ['Alice', 'Bob', 'Alice', 'Alice', 'Bob']
count = Counter(votes)
print(count)  # Counter({'Alice': 3, 'Bob': 2})

  1. 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})
    

  2. 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
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd)  # defaultdict(<class 'int'>, {'a': 1})

  1. 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
x = 10
y = 'Positive' if x > 0 else 'Negative'
print(y)  # Positive

  1. 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
numbers = [1, 2, 3, 4]
squares = [n**2 for n in numbers]
print(squares)  # [1, 4, 9, 16]

  1. 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
values = [0, 0, 1]
print(any(values))  # True

  1. 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
def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
display_info(name='Alice', age=25)

  1. Unpacking into Function Calls
    1
    2
    data = {'name': 'Bob', 'age': 30}
    display_info(**data)
    

Activities

  1. Set Operations: Find common and unique elements between two lists.
  2. Counter Applications: Write a program to count votes and find the winner.
  3. Defaultdict Usage: Implement a function to group words by their first letter.
  4. List Comprehensions: Create a list of even numbers from 1 to 20.
  5. any and all: Check if a list contains only positive numbers.