FlashKeepers

Python · Python

Python Data Structures and Comprehensions

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.

Study this set free Look inside first Get FlashKeepers for iPhone
What is the syntax for a basic list comprehension?
[expression for item in iterable]
How do you add a condition to a list comprehension?
[expression for item in iterable if condition]
Write a list comprehension that squares numbers 1 to 5
[x**2 for x in range(1, 6)]
Write a list comprehension that keeps only even numbers from 0 to 10
[x for x in range(11) if x % 2 == 0]
How do you write nested loops in a list comprehension?
[x + y for x in list1 for y in list2]
What does [x if x > 0 else 0 for x in nums] do?
Replaces negative numbers with 0, keeps positive numbers
Write a list comprehension that converts strings to integers, keeping only valid ones
[int(x) for x in strings if x.isdigit()]
What is the syntax for a dict comprehension?
{key: value for item in iterable}
Write a dict comprehension that maps numbers to their squares
{x: x**2 for x in range(1, 6)}
How do you add a condition to a dict comprehension?
{key: value for item in iterable if condition}
Write a dict comprehension that swaps keys and values from an existing dict
{v: k for k, v in original_dict.items()}
Write a dict comprehension using zip to pair two lists
{k: v for k, v in zip(keys, values)}
What is the syntax for a set comprehension?
{expression for item in iterable}
Write a set comprehension that gets unique letters from a string
{char for char in 'hello world'}
How do you add a condition to a set comprehension?
{expression for item in iterable if condition}

20 more cards in the app