Lists are ordered, mutable collections. List comprehensions provide a concise way to create lists: [expression for item in iterable if condition].
# 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]
Create a list of squares of numbers 1 through 5 using a list comprehension. Print the list.
Loading Python runtime (Pyodide)...
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 runtime (Pyodide)...
Flatten [[1, 2], [3, 4], [5, 6]] into [1, 2, 3, 4, 5, 6] using a list comprehension. Print the result.
Loading Python runtime (Pyodide)...