Exercise Library

Size: Both · Mini · Full
add Sum up lists-of-lists of numbers
comprehensionslooping
Full
Circle Class representing a Circle, with auto-updating attributes
classespropertiesmath
Full
count_words Count occurrences of each word in a string
regular expressionsdictionariesloopingfunction
Full
tail Return last N items in a given iterable
iteration toollistloopingfunctionslicing
Full
parse_ranges Parse comma-delimited numeric ranges
regular expressionscomprehensionsgeneratorstext processingmaking iterators
Full
dollars Script to display a number as US currency
command line interfaces
Mini
to_percent Convert a ratio to a percentage
mathfunction
Mini
last_n_elements Get the last N items in a list
listconditionalsfunctionslicing
Mini
zero Command-line program that prints eighty 0's
loopingargument parsingcommand line interfaces
Mini
swap_ends Swap first and last items in a list
listfunction
Mini
split_in_half Split a list into two halves
listfunctionslicing
Mini
combine_lists Combine two lists into one
listloopingfunction
Mini
head Get the first N items from any iterable
iteration toolcomprehensionslistgeneratorsmaking iteratorsloopingfunction
Mini
characters Get a list of lowercased characters from a string
listsortingfunction
Mini
line_numbers Program to print lines from a file with their line numbers
loopingcommand line interfacesfunction
Mini
reverse_words Reverse words in the given string
listfunctionslicing
Mini
flip_dict Flip keys and values in a dictionary.
dictionarieslooping
Mini
Point Class representing a 3-dimensional point
classesdataclassesgeneratorsdunder methodsmaking iterators
Full
has_duplicates Determine whether a list has duplicate items
listloopingslicing
Mini
jot Script for quickly jotting down ideas for later
command line interfacesfile navigation
Mini
len_or_none Return return the length or None (if no length)
exception handlingfunction
Mini
is_anagram Determine whether the given words are anagrams
dictionariestext processingunicodefunction
Full
total_air_travel Add up all air travel expenses in a CSV file
csvfile processingargument parsingcommand line interfaces
Mini
lucas Generate numbers from the Lucas sequence in your terminal
text processingcommand line interfaces
Full
transpose Transpose a given list-of-lists
comprehensionslistloopingfunction
Mini
fix_csv.py Convert pipe-delimited files to comma-delimited files
csvlistfile processingargument parsingcommand line interfaces
Full
matrix_from_string Turn a string into a list-of-lists of numbers
comprehensionsmathlistloopingfunction
Mini
rotate_list Rotate item from one end of a list to the other
listconditionals
Mini
dict_from_tuple Turn list-of-tuples into a multi-valued dictionary
dictionariesloopingfunction
Mini
NextDate Find date of the next given weekday
classesdataclasses
Full
roll Simulate dice rolls.
mathargument parsingcommand line interfaces
Mini
fix_newlines Enforce final newlines and normalize file line endings
text processingloopingfile processingcommand line interfacesconditionals
Full
meetup_date Find N-th occurrence of a specific weekday in the month
comprehensionsfunction
Full
is_perfect_square Determine whether a number is a perfect square
math
Full
sort_dict Sort a dictionary by its keys
dictionariessortinglooping
Mini
call_later Create a function to call another function at a later time
Mini
rock paper scissors Implement the game rock-paper-scissors
dictionariesargument parsingcommand line interfacesconditionals
Full
input_number Prompt a user to enter a number
exception handling
Mini
ProxyDict Immutable dictionary-like wrapper around a dictionary
classesmaking iterators
Full
to_jsonl Convert a JSON array file to a JSONL file
file processingcommand line interfaces
Mini
uniques_only Get unique items from an iterable while maintaining item order
iteration toollistgeneratorsmaking iteratorsloopingfunctionslicing
Full
print_call_time Decorator to the print time a function took to run
decorators
Mini
mask keys Mask sensitive dictionary keys
dictionariesrecursion
Full
duplicates_only Refactor duplicate-checking function to improve performance
dictionariesefficiency
Mini
jsonify Decorator to JSON-encode a function's return value
decorators
Mini
deep_add Deeply sum numbers in an iterable-of-iterables
recursionlooping
Full
strip_lines Get all lines from a file with newlines removed
iteration toolcomprehensionsgeneratorsmaking iteratorsloopingfile processingfunction
Mini
four Repeatedly count the letters within a number
mathtext processingloopingcommand line interfacesconditionals
Full
float_range range-like utility for floating point numbers
classesiteration toolmathgeneratorsdunder methodsloopingefficiency
Full
groot A decorator that always prints "Groot"
decorators
Mini
sum_timestamps Sum up a list of MM:SS timestamp strings
regular expressionscomprehensionsgenerators
Full
get_shared_keys Find the common keys between two dictionaries
dictionariesfunction
Mini
csv_columns Turn CSV rows into a dictionary mapping headers to columns
dictionariescomprehensionslistloopingfile processing
Full
first Get the first item from any iterable
Mini
BankAccount Class representing a bank account with read-only balance
classesproperties
Full
only_once Decorator that only allows functions to be called once
decorators
Mini
paste_code A function to help paste code into the Python REPL
loopingexception handlingfunction
Mini
format_ranges Format list of numbers into groups of start-stop strings
comprehensionslistgeneratorstext processingsortinglooping
Full
flatten_dict Flatten a dictionary-of-dictionaries
dictionariescomprehensionsrecursionlooping
Full
sort Sort the lines in a file
text processingsortingfile processingcommand line interfaces
Mini
window Get each iterable item and the next N-1 items
iteration toolgeneratorsdunder methodsmaking iteratorslooping
Full
Row Class that accepts any given keyword arguments
classes
Mini
suppress Context manager that suppresses specific exceptions
classescontext managersdataclassesdecoratorsgeneratorsexception handling
Full
is_iterator Determine whether an iterable is an iterator
Mini
chunked Break an iterable into N-length chunks
iteration toolcomprehensionsgeneratorsmaking iteratorsloopingslicing
Full
EasyDict Dictionary-like class supporting both attribute and key lookups
classes
Full
interleave Interleave items from each of the given iterables
iteration toolcomprehensionslistgeneratorsmaking iteratorslooping
Full
dramatic print Print text character-by-character
Full
reformat_diary.py Program to reformat a diary file into multiple files
regular expressionscomprehensionsgeneratorstext processingcommand line interfacesfile navigation
Full
PhoneNumber Class representing a US phone number
classesregular expressions
Full
format_fixed_width Format rows into a string of fixed-width columns
comprehensionslistgeneratorstext processingternary operator
Full
OrderedSet Set-like object that maintains insertion-order of items
classesgeneratorsdunder methodsmaking iteratorsefficiency
Full
tags_equal Determine whether two HTML tags are equivalent
regular expressionscomprehensionstext processingternary operatorslicing
Full
Month Class representing a month and year
classespropertiesdataclassesslotsdunder methodsefficiency
Full
minmax Return both minimum and maximum values in an iterable
dataclassesloopingternary operator
Full
count_calls Decorator that counts the calls to a function
classespropertiesdecorators
Full
maybe An object that is randomly truthy or falsey
classesdunder methods
Full
remove_empty Remove all empty directories recursively
command line interfaces
Mini
CyclicList List-like class that loops in a cyclic manner
classesiterable classgeneratorsmaking iterators
Full
deep_flatten Flatten deeply nested iterable-of-iterables
iteration toolrecursiongeneratorsmaking iteratorslooping
Full
print_call_info Create a decorator that prints function call info
decorators
Mini
all_same Determine whether all items in an iterable are the same
generatorsloopingfunction
Full
MaxCounter A Counter that can identify all most common keys
classes
Mini
Vector Class representing 3-dimensional vector
classesdataclassesslotsgeneratorsdunder methodsmaking iteratorsefficiency
Full
pluck Tool to deeply query a dictionary of dictionaries
dictionariesrecursiontext processingexception handling
Full
fixed2csv.py Convert fixed-width file to CSV file
csvcomprehensionslistgeneratorsloopingfile processingargument parsingcommand line interfacesslicing
Full
float_range (part 2) range-like utility for floating point numbers
classesiterable classiteration toolmathdunder methodsloopingefficiencyslicing
Full
window (part 2) Get each iterable item and the next N-1 items
iteration toolcomprehensionsgeneratorsmaking iteratorsloopingslicing
Full
count_lines Calculate line count for all .py files in a directory
classesdataclassestext processingexception handlingfile navigation
Full
alias A helper that (magically?) alias one attribute to another
classespropertiesdataclassesdescriptors
Full
total_length Find the number of items in all given iterables
comprehensionsgeneratorslooping
Full
PermaDict Dictionary-like objects which don't allow key updates
classesdunder methodsmaking iterators
Full
sort_by_column.py Program to sort a CSV file by specific columns
csvcomprehensionssortingfile processingargument parsingexception handlingcommand line interfaces
Full
FuzzyString String-like class supporting case-insensitive comparisons
classestext processingunicode
Full
minmax (part 2) Getting minimum and maximum values from an iterable (again)
dataclassescomprehensionsloopingternary operatorexception handling
Full
ReverseView A sequence-like class representing the reverse of a given sequence
classesmaking iterators
Full
Count votes Program to count votes for numerical options
regular expressionsdictionariestext processingcommand line interfaces
Full
Timer Context manager to time blocks of code
classescontext managersdecorators
Full
my_builtins Re-implement some built-in functions to learn how they work
generatorsloopingternary operatorexception handling
Full
loop_helper A utility to get helpful information while looping
comprehensionsgeneratorslooping
Full
RandomLooper Loop over iterable items in a random order
classesiterable classcomprehensionslistgeneratorsdunder methods
Full
divide Divide an iterable into N parts
iteration toolcomprehensionsgeneratorsmaking iteratorsslicing
Full
Unpacker Class supporting tuple unpacking of all attributes
classesiterable classdictionariesdunder methods
Full
grades Convert percentages to US-style grades and calculate GPAs
dictionariesmathternary operatorconditionalsfunction
Full
SequenceZip A fancy version of zip just for sequences
classescomprehensionsgeneratorsdunder methods
Full
ini2csv.py Program to convert INI file to a CSV file
regular expressionscsvtext processingfile processingargument parsingcommand line interfacesslicing
Full
Comparator Object to facilitate "almost equal" numerical comparisons
classescontext managersmath
Full
cd Context manager for temporarily changing directories
classescontext managersdataclasses
Full
markdownify Convert basic HTML to basic markdown
regular expressionstext processing
Full
running_mean Utility to calculate a running mean while looping
mathgeneratorsloopingfunction
Full
FancyReader CSV reader that returns friendly objects for each row
classesiterable classdictionariescsvmaking iteratorsfile processing
Full
condense_csv Condense CSV text, to use fewer rows and more columns
dictionariescsvcomprehensionstext processingfile processing
Full
Grouper Dict-like class which groups things using a key function
classesdunder methods
Full
int_to_roman Convert integers to Roman numerals and back
text processingexception handling
Full
MutableString String-like object that is mutable
classescontext managersdunder methodstext processing
Full
strict_zip Like zip, but raises an error for iterables of different lengths
iteration toolcomprehensionsgeneratorsmaking iteratorsexception handling
Full
make_file Context manager to create a temporary file
classescontext managers
Full
normalize_sentences Make sure sentences have two spaces between them
regular expressionstext processingloopingslicing
Full
PiecewiseRange Lazy iterable representing the concatenation of many ranges
classescomprehensionsgeneratorsdunder methodsternary operator
Full
natural_sort Sort strings case-insensitively and numerically
regular expressionscomprehensionstext processingsortingternary operator
Full
MonthDelta MonthDelta class that works along with Month class
classesdataclassesdunder methods
Full
Timer (redux) Reusable context manager to time code blocks, including splitting
classescontext managersdunder methodsconstructor
Full
ages Utilities related to working with birthdates and ages
text processing
Full
record_calls Decorator that records calls to a function
classesdataclassesdecorators
Full
last_lines Get the lines in a file in reverse order
regular expressionslisttext processingmaking iteratorsfile processingbinary filesslicing
Full
FancyReader (redux) A memory-efficient version of csv.DictReader
classespropertiesslotsefficiency
Full
loop_tracker An iterator with extra bells and whistles
propertiesiteration toolmaking iteratorsexception handling
Full
format_bytes Format numbers into human-readable byte sizes
regular expressionsmathtext processingloopingternary operatorslicing
Full
nostar A module that disallows * imports
Mini
cached_property Like the property decorator but values are cached
classespropertiesdecoratorsdescriptors
Full
fancy_input Like the built-in input function, but fancier
loopingcommand line interfaces
Full
SliceView A "view" into a sequence, like a lazy slice
iterable classmathrecursiongeneratorsmaking iterators
Full
update_reviews Update one CSV file based on another CSV file
csvcomprehensionsfile processingargument parsingcommand line interfaces
Full
ChainSequence Class to link sequences together
classes
Full
min_n Get the smallest n items in an iterable
listsortingslicing
Full
final_class Making classes which cannot be subclassed.
decoratorsmetaclassesconstructor
Full
concat_check.py Find implicit string concatenation in Python files
regular expressionsfile processingbinary filescommand line interfaces
Full
ProxyDict (redux) Immutable dictionary-like wrapper around a dictionary
classesmaking iterators
Full
file_looper Utility to open many files one after the other
comprehensionsgeneratorsmaking iteratorsfile processing
Full
grep A utility like the Linux/Unix grep command
regular expressionsmathtext processingloopingargument parsingcommand line interfaces
Full
RomanNumeral Class representing a Roman numeral
classesdunder methods
Full
coalesce "Coalesce" a NULL value to a specific default value
decoratorscomprehensionsternary operator
Full
computed_property Cached decorator that recomputes on specific attribute changes
classespropertiesdecoratorscomprehensionsdescriptors
Full
easyjson Convert a JSON string to a JavaScript-like object
classescomprehensionsrecursion
Full
find_duplicates Identifies duplicate files
file processingbinary filesefficiency
Full
Check-writing helper Program to help write the amount/date for a cheque
mathtext processingcommand line interfacesconditionals
Full
MinHeap A heap data structure
classesslotsefficiency
Full
pattern_rename.py Program to rename files from one naming scheme to a different naming scheme
regular expressionscommand line interfaces
Full
validators A descriptor that can only be assigned positive numbers
classesdescriptorsdunder methodsconstructorweak references
Full
smoosh Weirdly-named utilities to flatten iterable of iterables
regular expressionsrecursion
Full
iconv.py Convert text from one character encoding to another
unicodefile processingbinary filesargument parsingcommand line interfaces
Full
instance_tracker Class factory which allows classes to track instances of themselves
constructorweak references
Full
bullet points Utilities for parsing nested bullet points
classesdataclassesregular expressionscomprehensionsdunder methodstext processing
Full
phonetic.py Program to spell words using the NATO phonetic alphabet
dictionariestext processingunicodeargument parsingcommand line interfaces
Full
moviestats Utilities for asking questions of a JSON-based data file
dictionariescomprehensionslistsortingefficiency
Full
SSH log parser Functions to extract data from a compressed SSH log file
dataclassesregular expressions
Full
random_rename Program to to randomize filenames for blinded reviews
csvfile processingargument parsingcommand line interfaces
Full
partial Utility to partially evaluate functions
classesdecoratorscomprehensionsgenerators
Full
Version tests Tests for a Version class which represents a program version
classesdunder methodsexception handlingcommand line interfaces
Full
easyclass A handy custom extension of the dataclass decorator
classesdataclassesiterable classdecorators
Full
dmath Command-line utility for doing date math
exception handlingcommand line interfaces
Full
FieldTracker Class that tracks which attributes have changed
classesdictionariescomprehensions
Full
debug_calls Decorator that prints debug information for the called function
decoratorsintrospection
Full
passphrase Command-line program that randomly generates 4-word passphrases
argument parsingcommand line interfaces
Full
QueryList List-like class with methods for quick queries
classesiterable class
Full
annual_return Calculate financial return rate over many years
regular expressionstext processingcommand line interfaces
Full
plan_meeting Command-line program to help plan international meetings
regular expressionsfile processingargument parsingcommand line interfaces
Full
my_builtins (redux) Re-implement some built-in functions to learn how they work
classesgeneratorsloopingconstructorexception handling
Full
page Command-line tool for paginating text files by their lines
file processingargument parsingcommand line interfaces
Full
reprtools Utilities to help implement __repr__ methods
decoratorscomprehensionsintrospection
Full
SequenceZip (part 2) Like zip-like utility that can be looped over multiple times
classesgeneratorsdunder methods
Full
positional_only Decorator requiring all arguments be positional-only arguments
classespropertiesdecoratorsconstructor
Full
Circle (redux) Class representing a Circle, with auto-updating attributes
classespropertiescomprehensionsmathefficiency
Full
checksum Program to validate file checksums
file processingbinary filescommand line interfaces
Full
iospy Utilities to merge file streams and spy on I/O
classescontext managersproperties
Full
EasyDict (part 2) Dictionary-like class supporting both attribute and key lookups
classes
Full
countdown Command-line visual countdown timer
comprehensionscommand line interfaces
Full
fancy_map Like the built-in map function but can be looped over many times
classesiteration tooldunder methodsmaking iterators
Full
crossword helper Command line util to generate crossword matches based on pattern
regular expressionsargument parsingcommand line interfaces
Full
Tree Tree-like data structure that automatically spawns new branches
classesdictionariesrecursiondunder methods
Full
bind Like functools.partial, but with placeholder arguments
dunder methods
Full
fixed2csv2.py Program to convert fixed-width files to CSV files
regular expressionscsvcomprehensionslistloopingfile processingcommand line interfacesslicing
Full
easyjson (redux) Convert a JSON string to a JavaScript-like object
classesslots
Full
diff_cols Program to compare specific columns in CSV files
csvargument parsingcommand line interfaces
Full
ratelimit Decorator to rate-limit calls to a function
classesdecorators
Full
zipit A CLI for making ZIP files from Python programs
binary filescommand line interfaces
Full
coalesce_args Decorator to "coalesce" arguments to their default values
decoratorsintrospection
Full
HistoryDict Dictionary-like structure that tracks previous item values
classes
Full
tee.py Command-line program to pipe standard input into given files
regular expressionscomprehensionstext processingbinary filesargument parsingcommand line interfacesfile navigation
Full
track_instances Track all instances of the decorated classes
classesslotsmetaclassesgeneratorsdunder methodsconstructorweak references
Full
peekable Iterator that can peek at the next item without consuming it
classesiteration tooldunder methodsmaking iteratorsexception handling
Full
OrderedSet (redux) Set-like object that maintains insertion-order of items
classesmaking iteratorsefficiency
Full
make_class Class factory function
classesefficiency
Full
lines2.py Command-line program to calculate line counts by file type
dataclassescomprehensionsgeneratorstext processingternary operatorargument parsingcommand line interfacesfile navigation
Full
snake_case Utilities to allow "snake_case" usage in a class with "camelCase" methods
classesregular expressionsdecorators
Full
sqlite ORM Lightweight SQLite database orm
classes
Full
dups.py Command-line utility for identifying duplicate files
file processingbinary filesargument parsingefficiencycommand line interfaces
Full
class_property A combination of property decorator and classmethod decorator
classesdecoratorsdescriptors
Full
gz Command-line program compresses (gzips) a given file
file processingbinary filesargument parsingcommand line interfaces
Full
Vector (redux) Class representing 3-dimensional vector
classesdataclassesslotsmaking iteratorsefficiency
Full
SuperMap Class that stores objects based on specific attribute values
classesdunder methods
Full
split Command line program to split a file into smaller files
comprehensionsgeneratorstext processingargument parsingcommand line interfaces
Full
OrderedDict Like collections.OrderedDict but with indexable keys
classesslotsgeneratorsdunder methodsmaking iterators
Full
reloopable Reset iterator each time looping over a file
classescontext managersmaking iteratorsfile processingfile navigation
Full
fancy_iterable A utility that lazily performs various operations on a given iterable
iterable class
Full
warningutils Raise exceptions when warnings are issued
classescontext managersdataclassesgeneratorsdunder methodsexception handling
Full
dunder_all Utilities to help populate a modules' __all__ attribute
context managersintrospection
Full
bullet points (redux) Utilities for parsing nested bullet points along with notes
classesdataclassesregular expressionscomprehensionsdunder methodstext processing
Full
mutable_hash Function to hash common mutable types
slotsrecursionlist
Full
replr A Python REPL that can save and restore its session state
binary filescommand line interfaces
Full
pattern_rename2.py Program to rename files from one naming scheme to a different naming scheme
regular expressionsargument parsingcommand line interfaces
Full
RandomNumber A class attribute that generates new data on each access
classespropertiesdescriptorsmathdunder methods
Full
HistoryDict (redux) Dictionary-like structure that tracks previous item values
classes
Full
overload Decorator for function overloading (based on argument number and types)
classesdecoratorsgeneratorsexception handling
Full
at A utility for chaining decorator functions together
decoratorsmetaclasses
Full
fancy_enums A series of custom enumeration classes
iterable classmetaclasses
Full

Track your progress

Sign Up Now or Log in to track which exercises you've solved, get personalized recommendations, and access exercise paths.