List, dict, and set comprehensions plus common built in data structure methods, each explained with a short example.
35 cards · basic cards · AI-written, checked twice. Edit anything.
- What is the syntax for a basic list comprehension?
Show answer
[expression for item in iterable]
- How do you add a condition to a list comprehension?
Show answer
[expression for item in iterable if condition]
- Write a list comprehension that squares numbers 1 to 5
Show answer
[x**2 for x in range(1, 6)]
- Write a list comprehension that keeps only even numbers from 0 to 10
Show answer
[x for x in range(11) if x % 2 == 0]
- How do you write nested loops in a list comprehension?
Show answer
[x + y for x in list1 for y in list2]
- What does [x if x > 0 else 0 for x in nums] do?
Show answer
Replaces negative numbers with 0, keeps positive numbers
- Write a list comprehension that converts strings to integers, keeping only valid ones
Show answer
[int(x) for x in strings if x.isdigit()]
- What is the syntax for a dict comprehension?
Show answer
{key: value for item in iterable}
- Write a dict comprehension that maps numbers to their squares
Show answer
{x: x**2 for x in range(1, 6)}
- How do you add a condition to a dict comprehension?
Show answer
{key: value for item in iterable if condition}
- Write a dict comprehension that swaps keys and values from an existing dict
Show answer
{v: k for k, v in original_dict.items()}
- Write a dict comprehension using zip to pair two lists
Show answer
{k: v for k, v in zip(keys, values)}
- What is the syntax for a set comprehension?
Show answer
{expression for item in iterable}
- Write a set comprehension that gets unique letters from a string
Show answer
{char for char in 'hello world'}
- How do you add a condition to a set comprehension?
Show answer
{expression for item in iterable if condition}