Comprehensions
Comprehensions provide a concise way to create lists, dictionaries, and sets from existing collections.1. List Comprehensions
Create a new list by applying an expression to each item in a loop.2. Dictionary Comprehensions
Create a dictionary dynamically:3. Set Comprehensions
Similar to lists, but returns unique elements:Iterators
An iterator is an object representing a stream of data. It yields one element at a time when you callnext() on it.
The Iterator Protocol
To make an object iterable, it must implement two methods:__iter__(): Returns the iterator object itself.__next__(): Returns the next value in the stream. If there are no more values, it raises theStopIterationexception.
Generators
Generators are a simple way to create iterators using theyield keyword. Unlike standard functions that use return and exit, a generator function pauses and yields a value to the caller, remembering its state for the next call.
1. Generator Functions
2. Generator Expressions
Syntactically similar to list comprehensions, but wrapped in parentheses(). They do not store values in memory; instead, they generate items on demand:
Context Managers
Context Managers manage resources, ensuring that files, database connections, or locks are properly acquired and released.The with Statement
The most common way to use context managers is via with.
Creating Custom Context Managers
You can create custom context managers using thecontextmanager decorator from Python’s built-in contextlib library:
Practice & Exercises
To reinforce what you’ve learned in this section (List/Dict/Set comprehensions, custom iterators, generators, and context managers), practice with these interactive notebooks:Follow-Along Practice
Practice creating list transformations, dictionary mappings, set aggregations, custom iterable objects, yield generators, lazy-evaluated expressions, and custom context managers.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises on filtering capitalized list items, dictionary character mapping, custom even sequence iterator classes, and managed file context wrappers.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now let’s explore Functional Programming paradigms in Python, including map, filter, and reduce operations!Functional Programming
Learn map, filter, and reduce functions