Python Basics

List Comprehension in Python

A list comprehension expresses a loop, optional condition, and resulting value in one readable expression.

What is List Comprehension?

A list comprehension expresses a loop, optional condition, and resulting value in one readable expression.

Transform and filter values with a Python list comprehension.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
numbers = range(1, 11)
even_squares = [number ** 2 for number in numbers if number % 2 == 0]

print(even_squares)

Expected output

[4, 16, 36, 64, 100]

How it works

The condition keeps even values and the expression squares each value that passes the filter.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →