Python/🐍 Python Foundations/Lists & Comprehensions

Lists & Comprehensions

Lists are ordered, mutable collections. List comprehensions provide a concise way to create lists: [expression for item in iterable if condition].

Guided Example

# Example: List comprehension
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)  # [1, 4, 9, 16, 25]

evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4]

Practice Problems (0/3 solved)

Easy

List of Squares

Create a list of squares of numbers 1 through 5 using a list comprehension. Print the list.

Loading Python...
Loading...

Loading Python runtime (Pyodide)...

Easy

Filter Even Numbers

From the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], create a new list with only even numbers using a list comprehension. Print it.

Loading Python...
Loading...

Loading Python runtime (Pyodide)...

Hard

Flatten Nested List

Flatten [[1, 2], [3, 4], [5, 6]] into [1, 2, 3, 4, 5, 6] using a list comprehension. Print the result.

Loading Python...
Loading...

Loading Python runtime (Pyodide)...