Skip to main content
Writing “Pythonic” code means utilizing Python’s unique features to make code clean, readable, and highly expressive. A primary example of this pythonic programming style is using Comprehensions to transform and filter collections, alongside other advanced constructs like Iterators, Generators, and Context Managers.

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 call next() on it.

The Iterator Protocol

To make an object iterable, it must implement two methods:
  1. __iter__(): Returns the iterator object itself.
  2. __next__(): Returns the next value in the stream. If there are no more values, it raises the StopIteration exception.

Generators

Generators are a simple way to create iterators using the yield 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:
Memory Advantage: Generators are highly memory-efficient. Use them when working with massive datasets or infinite streams (e.g., reading large log files line-by-line).

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 the contextmanager 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