Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

MODULE 11: Advanced Python Concepts

1. List & Dictionary Comprehensions

Comprehensions provide a concise way to create collections. They are faster and more readable than traditional for loops.

Example:

Python

# List Comprehension: [expression for item in iterable]
squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

# Dictionary Comprehension: {key: value for item in iterable}
prices = {"apple": 1, "banana": 2}
double_prices = {k: v*2 for k, v in prices.items()}

2. Generators & Iterators

  • Iterators: Objects that can be iterated upon (using next()).
  • Generators: Functions that use yield instead of return. They generate values on the fly, saving massive amounts of memory.

Example:

Python

def count_up_to(n):
    i = 1
    while i <= n:
        yield i  # Pauses here and returns value
        i += 1

counter = count_up_to(1000000) # Memory efficient!

3. Closures

A closure is a nested function that “remembers” the values from its enclosing scope even after the outer function has finished executing.

Example:

Python

def multiplier(n):
    def multiply(x):
        return x * n
    return multiply

times3 = multiplier(3)
print(times3(10)) # 30

4. Decorators

Decorators allow you to modify or “wrap” the behavior of a function without changing its source code. They are commonly used for logging, timing, or authentication.

Example:

Python

def my_decorator(func):
    def wrapper():
        print("Something before.")
        func()
        print("Something after.")
    return wrapper

@my_decorator
def say_hi():
    print("Hi!")

5. Context Managers

Context managers handle the setup and teardown of resources (like opening and closing files). You implement them using the with statement.

6. Multithreading vs. Multiprocessing

  • Multithreading: Runs multiple threads within a single process. Best for I/O-bound tasks (like downloading files).
  • Multiprocessing: Runs multiple processes on different CPU cores. Best for CPU-bound tasks (like heavy math).

7. Async & Await (Asynchronous Programming)

Asynchronous programming allows your code to handle multiple tasks concurrently without needing multiple CPU cores. It is widely used in web servers and network applications.

Example:

Python

import asyncio

async def say_hello():
    print("Hello...")
    await asyncio.sleep(1) # Non-blocking sleep
    print("...World!")

asyncio.run(say_hello())

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥