C#
PY

C# to Python

10 lessons

Progress0%
1Introduction2Type Systems3Functions4Collections5Object-Oriented Programming6LINQ to Comprehensions7Async Programming8Ecosystem9Decorators and Metaprogramming10Error Handling
All Mirror Courses
C#
PY
LINQ to Comprehensions
MirrorLesson 6 of 10
Lesson 6

LINQ to Comprehensions

LINQ to Comprehensions

Introduction

In this lesson, you'll learn about linq to comprehensions in Python. Coming from C#, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
C#
From C#:

In C#, you're familiar with linq to comprehensions.

PY
In Python:

Python has its own approach to linq to comprehensions, which we'll explore step by step.

The Python Way

Let's see how Python handles this concept. Here's a typical example:

PY
Python Example
# List comprehension (filter + transform)
evens = [n * 2 for n in numbers if n % 2 == 0]

# Dict comprehension
squares = {n: n**2 for n in range(10)}

# Set comprehension
unique_lengths = {len(s) for s in strings}

# Generator (lazy, like unevaluated LINQ)
gen = (n * 2 for n in numbers if n % 2 == 0)

Comparing to C#

Here's how you might have written similar code in C#:

C#
C# (What you know)
// Filter + transform
var evens = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * 2)
    .ToList();

// Query syntax
var query = from n in numbers
            where n > 0
            select n * n;
Mirror Card
C#
From C#:

You may be used to different syntax or behavior.

PY
In Python:

List comprehensions replace LINQ Where + Select + ToList() in one line

Mirror Card
C#
From C#:

You may be used to different syntax or behavior.

PY
In Python:

Comprehension syntax: [expression for item in iterable if condition]

Mirror Card
C#
From C#:

You may be used to different syntax or behavior.

PY
In Python:

Python also has dict comprehensions {} and set comprehensions {}

Mirror Card
C#
From C#:

You may be used to different syntax or behavior.

PY
In Python:

Generator expressions use () and are lazy, like un-materialized LINQ

Mirror Card
C#
From C#:

You may be used to different syntax or behavior.

PY
In Python:

For complex pipelines, chained calls to filter() and map() also work

Step-by-Step Breakdown

1. Basic List Comprehension

A list comprehension combines filter and transform into a single readable expression. The condition at the end is optional.

C#
C#
var doubled = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * 2)
    .ToList();
PY
Python
doubled = [n * 2 for n in numbers if n % 2 == 0]

# Read as: "n*2 for each n in numbers where n is even"
Rule of Thumb
If the comprehension fits on one line and is easy to read, use it. Otherwise, write a regular for loop — readability wins.

2. Dict and Set Comprehensions

The same syntax extends to dicts and sets. Dict comprehensions use key: value syntax inside {}.

C#
C#
var squared = numbers
    .ToDictionary(n => n, n => n * n);
PY
Python
squared = {n: n**2 for n in numbers}

# Set comprehension (unique values)
lengths = {len(word) for word in words}

3. Nested Comprehensions

Comprehensions can be nested for multi-dimensional data — like nested LINQ SelectMany.

C#
C#
var flat = matrix
    .SelectMany(row => row)
    .ToList();
PY
Python
# Flatten a 2D list
flat = [x for row in matrix for x in row]

# Equivalent with nested loops:
flat = []
for row in matrix:
    for x in row:
        flat.append(x)
Common Pitfall
The order in nested comprehensions matches the order of nested for loops — the outer loop comes first, left to right.

4. Generators — Lazy Evaluation

Generator expressions use () instead of []. They are lazy — values are computed on demand, exactly like non-materialized LINQ queries.

C#
C#
// C# - lazy LINQ (not yet evaluated)
IEnumerable<int> lazy = numbers.Where(n => n > 0);
// Evaluated only when iterated
PY
Python
# Generator expression — lazy
lazy = (n * 2 for n in numbers if n > 0)

# Iterating triggers computation:
for val in lazy:
    print(val)

# Or materialize:
result = list(lazy)
Rule of Thumb
Use generator expressions when you only need to iterate once and don't need random access. They use far less memory than list comprehensions for large data.

Common Mistakes

When coming from C#, developers often make these mistakes:

  • List comprehensions replace LINQ Where + Select + ToList() in one line
  • Comprehension syntax: [expression for item in iterable if condition]
  • Python also has dict comprehensions {} and set comprehensions {}
Common Pitfall
Don't assume Python works exactly like C#. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • [expr for x in iterable if cond] replaces Where + Select + ToList()
  • Dict {k: v for ...} and set {v for ...} comprehensions follow the same pattern
  • Use () for lazy generator expressions (like non-materialized LINQ)
  • Keep comprehensions short — use a for loop when readability suffers
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your C# code in Python to practice these concepts.
PreviousNext