Python Snippets



Calculates the date of n days from the given date.

  • Use datetime.timedelta and the + operator to calculate the new datetime.datetime value after adding n days to d.

  • Omit the second argument, d, to use a default value of datetime.today().

from datetime import datetime, timedelta

def add_days(n, d = datetime.today()):
  return d + timedelta(n)
from datetime import date

add_days(5, date(2020, 10, 25)) # date(2020, 10, 30)
add_days(-5, date(2020, 10, 25)) # date(2020, 10, 20)


Checks if all elements in a list are equal.

  • Use set() to eliminate duplicate elements and then use len() to check if length is 1.

def all_equal(lst):
  return len(set(lst)) == 1


Checks if all the values in a list are unique.

  • Use set() on the given list to keep only unique occurrences.

  • Use len() to compare the length of the unique values to the original list.



Generates a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit.

  • Use range() and list() with the appropriate start, step and end values.



Calculates the average of two or more numbers.

  • Use sum() to sum all of the args provided, divide by len().



Calculates the average of a list, after mapping each element to a value using the provided function.

  • Use map() to map each element to the value returned by fn.

  • Use sum() to sum all of the mapped values, divide by len(lst).

  • Omit the last argument, fn, to use the default identity function.



Splits values into two groups, based on the result of the given filter list.

  • Use a list comprehension and zip() to add elements to groups, based on filter.

  • If filter has a truthy value for any element, add it to the first group, otherwise add it to the second group.



Splits values into two groups, based on the result of the given filtering function.

  • Use a list comprehension to add elements to groups, based on the value returned by fn for each element.

  • If fn returns a truthy value for any element, add it to the first group, otherwise add it to the second group.



Calculates the number of ways to choose k items from n items without repetition and without order.

  • Use math.comb() to calculate the binomial coefficient.



Returns the length of a string in bytes.

  • Use str.encode('utf-8') to encode the given string and return its length.



Converts a string to camelcase.

  • Use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+".

  • Use str.title() to capitalize the first letter of each word and convert the rest to lowercase.

  • Finally, use str.replace() to remove spaces between words.



Capitalizes the first letter of a string.

  • Use list slicing and str.upper() to capitalize the first letter of the string.

  • Use str.join() to combine the capitalized first letter with the rest of the characters.

  • Omit the lower_rest parameter to keep the rest of the string intact, or set it to True to convert to lowercase.



Capitalizes the first letter of every word in a string.

  • Use str.title() to capitalize the first letter of every word in the string.



Casts the provided value as a list if it's not one.

  • Use isinstance() to check if the given value is enumerable.

  • Return it by using list() or encapsulated in a list accordingly.


unlisted: true

Converts Celsius to Fahrenheit.

  • Follow the conversion formula F = 1.8 * C + 32.



Creates a function that will invoke a predicate function for the specified property on a given object.

  • Return a lambda function that takes an object and applies the predicate function, fn to the specified property.



Chunks a list into smaller lists of a specified size.

  • Use list() and range() to create a list of the desired size.

  • Use map() on the list and fill it with splices of the given list.

  • Finally, return the created list.



Chunks a list into n smaller lists.

  • Use math.ceil() and len() to get the size of each chunk.

  • Use list() and range() to create a new list of size n.

  • Use map() to map each element of the new list to a chunk the length of size.

  • If the original list can't be split evenly, the final chunk will contain the remaining elements.



Clamps num within the inclusive range specified by the boundary values.

  • If num falls within the range (a, b), return num.

  • Otherwise, return the nearest number in the range.



Inverts a dictionary with non-unique hashable values.

  • Create a collections.defaultdict with list as the default value for each key.

  • Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

  • Use dict() to convert the collections.defaultdict to a regular dictionary.



Combines two or more dictionaries, creating a list of values for each key.

  • Create a new collections.defaultdict with list as the default value for each key and loop over dicts.

  • Use dict.append() to map the values of the dictionary to keys.

  • Use dict() to convert the collections.defaultdict to a regular dictionary.



Removes falsy values from a list.

  • Use filter() to filter out falsy values (False, None, 0, and "").



Performs right-to-left function composition.

  • Use functools.reduce() to perform right-to-left function composition.

  • The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.



Performs left-to-right function composition.

  • Use functools.reduce() to perform left-to-right function composition.

  • The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.



Groups the elements of a list based on the given function and returns the count of elements in each group.

  • Use collections.defaultdict to initialize a dictionary.

  • Use map() to map the values of the given list using the given function.

  • Iterate over the map and increase the element count each time it occurs.



Counts the occurrences of a value in a list.

  • Use list.count() to count the number of occurrences of val in lst.



Creates a list of partial sums.

  • Use itertools.accumulate() to create the accumulated sum for each element.

  • Use list() to convert the result into a list.



Curries a function.

  • Use functools.partial() to return a new partial object which behaves like fn with the given arguments, args, partially applied.



Creates a list of dates between start (inclusive) and end (not inclusive).

  • Use datetime.timedelta.days to get the days between start and end.

  • Use int() to convert the result to an integer and range() to iterate over each day.

  • Use a list comprehension and datetime.timedelta() to create a list of datetime.date objects.



Calculates the date of n days ago from today.

  • Use datetime.date.today() to get the current day.

  • Use datetime.timedelta to subtract n days from today's date.



Calculates the day difference between two dates.

  • Subtract start from end and use datetime.timedelta.days to get the day difference.



Calculates the date of n days from today.

  • Use datetime.date.today() to get the current day.

  • Use datetime.timedelta to add n days from today's date.



Decapitalizes the first letter of a string.

  • Use list slicing and str.lower() to decapitalize the first letter of the string.

  • Use str.join() to combine the lowercase first letter with the rest of the characters.

  • Omit the upper_rest parameter to keep the rest of the string intact, or set it to True to convert to uppercase.



Deep flattens a list.

  • Use recursion.

  • Use isinstance() with collections.abc.Iterable to check if an element is iterable.

  • If it is iterable, apply deep_flatten() recursively, otherwise return [lst].



Converts an angle from degrees to radians.

  • Use math.pi and the degrees to radians formula to convert the angle from degrees to radians.



Invokes the provided function after ms milliseconds.

  • Use time.sleep() to delay the execution of fn by ms / 1000 seconds.



Converts a dictionary to a list of tuples.

  • Use dict.items() and list() to get a list of tuples from the given dictionary.



Calculates the difference between two iterables, without filtering duplicate values.

  • Create a set from b.

  • Use a list comprehension on a to only keep values not contained in the previously created set, _b.



Returns the difference between two lists, after applying the provided function to each list element of both.

  • Create a set, using map() to apply fn to each element in b.

  • Use a list comprehension in combination with fn on a to only keep values not contained in the previously created set, _b.



Converts a number to a list of digits.

  • Use map() combined with int on the string representation of n and return a list from the result.



Returns a list with n elements removed from the left.

  • Use slice notation to remove the specified number of elements from the left.

  • Omit the last argument, n, to use a default value of 1.



Returns a list with n elements removed from the right.

  • Use slice notation to remove the specified number of elements from the right.

  • Omit the last argument, n, to use a default value of 1.



Checks if the provided function returns True for every element in the list.

  • Use all() in combination with map() and fn to check if fn returns True for all elements in the list.



Returns every nth element in a list.

  • Use slice notation to create a new list that contains every nth element of the given list.



Calculates the factorial of a number.

  • Use recursion.

  • If num is less than or equal to 1, return 1.

  • Otherwise, return the product of num and the factorial of num - 1.

  • Throws an exception if num is a negative or a floating point number.


unlisted: true

Converts Fahrenheit to Celsius.

  • Follow the conversion formula C = (F - 32) * 5/9.



Generates a list, containing the Fibonacci sequence, up until the nth term.

  • Starting with 0 and 1, use list.append() to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches n.

  • If n is less or equal to 0, return a list containing 0.



Creates a list with the non-unique values filtered out.

  • Use collections.Counter to get the count of each value in the list.

  • Use a list comprehension to create a list containing only the unique values.



Creates a list with the unique values filtered out.

  • Use collections.Counter to get the count of each value in the list.

  • Use a list comprehension to create a list containing only the non-unique values.



Finds the value of the first element in the given list that satisfies the provided testing function.

  • Use a list comprehension and next() to return the first element in lst for which fn returns True.



Finds the index of the first element in the given list that satisfies the provided testing function.

  • Use a list comprehension, enumerate() and next() to return the index of the first element in lst for which fn returns True.



Finds the indexes of all elements in the given list that satisfy the provided testing function.

  • Use enumerate() and a list comprehension to return the indexes of the all element in lst for which fn returns True.



Finds the first key in the provided dictionary that has the given value.

  • Use dictionary.items() and next() to return the first key that has a value equal to val.



Finds all keys in the provided dictionary that have the given value.

  • Use dictionary.items(), a generator and list() to return all keys that have a value equal to val.



Finds the value of the last element in the given list that satisfies the provided testing function.

  • Use a list comprehension and next() to return the last element in lst for which fn returns True.



Finds the index of the last element in the given list that satisfies the provided testing function.

  • Use a list comprehension, enumerate() and next() to return the index of the last element in lst for which fn returns True.



Finds the items that are parity outliers in a given list.

  • Use collections.Counter with a list comprehension to count even and odd values in the list.

  • Use collections.Counter.most_common() to get the most common parity.

  • Use a list comprehension to find all elements that do not match the most common parity.



Flattens a list of lists once.

  • Use a list comprehension to extract each value from sub-lists in order.



Executes the provided function once for each list element.

  • Use a for loop to execute fn for each element in itr.



Executes the provided function once for each list element, starting from the list's last element.

  • Use a for loop in combination with slice notation to execute fn for each element in itr, starting from the last one.



Creates a dictionary with the unique values of a list as keys and their frequencies as the values.

  • Use collections.defaultdict() to store the frequencies of each unique element.

  • Use dict() to return a dictionary with the unique elements of the list as keys and their frequencies as the values.



Converts a date from its ISO-8601 representation.

  • Use datetime.datetime.fromisoformat() to convert the given ISO-8601 date to a datetime.datetime object.



Calculates the greatest common divisor of a list of numbers.

  • Use functools.reduce() and math.gcd() over the given list.



Initializes a list containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step.

Returns an error if step equals 1.

  • Use range(), math.log() and math.floor() and a list comprehension to create a list of the appropriate length, applying the step for each element.

  • Omit the second argument, start, to use a default value of 1.

  • Omit the third argument, step, to use a default value of 2.



Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.

  • Use functools.reduce() to iterate over the selectors list.

  • Apply operator.getitem() for each key in selectors, retrieving the value to be used as the iteratee for the next iteration.



Groups the elements of a list based on the given function.

  • Use collections.defaultdict to initialize a dictionary.

  • Use fn in combination with a for loop and dict.append() to populate the dictionary.

  • Use dict() to convert it to a regular dictionary.



Calculates the Hamming distance between two values.

  • Use the XOR operator (^) to find the bit difference between the two numbers.

  • Use bin() to convert the result to a binary string.

  • Convert the string to a list and use count() of str class to count and return the number of 1s in it.



Checks if there are duplicate values in a flat list.

  • Use set() on the given list to remove duplicates, compare its length with the length of the list.



Checks if two lists contain the same elements regardless of order.

  • Use set() on the combination of both lists to find the unique values.

  • Iterate over them with a for loop comparing the count() of each unique value in each list.

  • Return False if the counts do not match for any element, True otherwise.



Returns the head of a list.

  • Use lst[0] to return the first element of the passed list.



Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.

  • Use a list comprehension in combination with int() and list slice notation to get the RGB components from the hexadecimal string.

  • Use tuple() to convert the resulting list to a tuple.



Checks if the given number falls within the given range.

  • Use arithmetic comparison to check if the given number is in the specified range.

  • If the second parameter, end, is not specified, the range is considered to be from 0 to start.



Checks if all the elements in values are included in lst.

  • Check if every value in values is contained in lst using a for loop.

  • Return False if any one value is not found, True otherwise.



Checks if any element in values is included in lst.

  • Check if any value in values is contained in lst using a for loop.

  • Return True if any one value is found, False otherwise.



Returns a list of indexes of all the occurrences of an element in a list.

  • Use enumerate() and a list comprehension to check each element for equality with value and adding i to the result.



Returns all the elements of a list except the last one.

  • Use lst[:-1] to return all but the last element of the list.



Initializes a 2D list of given width and height and value.

  • Use a list comprehension and range() to generate h rows where each is a list with length h, initialized with val.

  • Omit the last argument, val, to set the default value to None.



Initializes a list containing the numbers in the specified range where start and end are inclusive with their common difference step.

  • Use list() and range() to generate a list of the appropriate length, filled with the desired values in the given range.

  • Omit start to use the default value of 0.

  • Omit step to use the default value of 1.



Initializes and fills a list with the specified value.

  • Use a list comprehension and range() to generate a list of length equal to n, filled with the desired values.

  • Omit val to use the default value of 0.



Returns a list of elements that exist in both lists.

  • Create a set from a and b.

  • Use the built-in set operator & to only keep values contained in both sets, then transform the set back into a list.



Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.

  • Create a set, using map() to apply fn to each element in b.

  • Use a list comprehension in combination with fn on a to only keep values contained in both lists.



Inverts a dictionary with unique hashable values.

  • Use dictionary.items() in combination with a list comprehension to create a new dictionary with the values and keys inverted.



Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

  • Use str.isalnum() to filter out non-alphanumeric characters, str.lower() to transform each character to lowercase.

  • Use collections.Counter to count the resulting characters for each string and compare the results.



Checks if the elements of the first list are contained in the second one regardless of order.

  • Use count() to check if any value in a has more occurrences than it has in b.

  • Return False if any such value is found, True otherwise.


unlisted: true

Checks if the first numeric argument is divisible by the second one.

  • Use the modulo operator (%) to check if the remainder is equal to 0.


unlisted: true

Checks if the given number is even.

  • Check whether a number is odd or even using the modulo (%) operator.

  • Return True if the number is even, False if the number is odd.


unlisted: true

Checks if the given number is odd.

  • Checks whether a number is even or odd using the modulo (%) operator.

  • Returns True if the number is odd, False if the number is even.



Checks if the provided integer is a prime number.

  • Return False if the number is 0, 1, a negative number or a multiple of 2.

  • Use all() and range() to check numbers from 3 to the square root of the given number.

  • Return True if none divides the given number, False otherwise.



Checks if the given date is a weekday.

  • Use datetime.datetime.weekday() to get the day of the week as an integer.

  • Check if the day of the week is less than or equal to 4.

  • Omit the second argument, d, to use a default value of datetime.today().



Checks if the given date is a weekend.

  • Use datetime.datetime.weekday() to get the day of the week as an integer.

  • Check if the day of the week is greater than 4.

  • Omit the second argument, d, to use a default value of datetime.today().



Converts a string to kebab case.

  • Use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+".

  • Use re.sub() to match all words in the string, str.lower() to lowercase them.

  • Finally, use str.join() to combine all word using - as the separator.



Checks if the given key exists in a dictionary.

  • Use the in operator to check if d contains key.



Finds the key of the maximum value in a dictionary.

  • Use max() with the key parameter set to dict.get() to find and return the key of the maximum value in the given dictionary.



Finds the key of the minimum value in a dictionary.

  • Use min() with the key parameter set to dict.get() to find and return the key of the minimum value in the given dictionary.



Creates a flat list of all the keys in a flat dictionary.

  • Use dict.keys() to return the keys in the given dictionary.

  • Return a list() of the previous result.


unlisted: true

Converts kilometers to miles.

  • Follows the conversion formula mi = km * 0.621371.



Returns the last element in a list.

  • Use lst[-1] to return the last element of the passed list.



Returns the least common multiple of a list of numbers.

  • Use functools.reduce(), math.gcd() and lcm(x,y) = x * y / gcd(x,y) over the given list.



Takes any number of iterable objects or objects with a length property and returns the longest one.

  • Use max() with len() as the key to return the item with the greatest length.

  • If multiple objects have the same length, the first one will be returned.



Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.

  • Use map() to apply fn to each value of the list.

  • Use zip() to pair original values to the values produced by fn.

  • Use dict() to return an appropriate dictionary.



Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.

  • Use dict.items() to iterate over the dictionary, assigning the values produced by fn to each key of a new dictionary.



Returns the maximum value of a list, after mapping each element to a value using the provided function.

  • Use map() with fn to map each element to a value using the provided function.

  • Use max() to return the maximum value.



Returns the index of the element with the maximum value in a list.

  • Use max() and list.index() to get the maximum value in the list and return its index.



Returns the n maximum elements from the provided list.

  • Use sorted() to sort the list.

  • Use slice notation to get the specified number of elements.

  • Omit the second argument, n, to get a one-element list.

  • If n is greater than or equal to the provided list's length, then return the original list (sorted in descending order).



Finds the median of a list of numbers.

  • Sort the numbers of the list using list.sort().

  • Find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.

  • statistics.median() provides similar functionality to this snippet.



Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.

  • Use max() combined with a list comprehension to get the length of the longest list in the arguments.

  • Use range() in combination with the max_length variable to loop as many times as there are elements in the longest list.

  • If a list is shorter than max_length, use fill_value for the remaining items (defaults to None).

  • zip() and itertools.zip_longest() provide similar functionality to this snippet.



Merges two or more dictionaries.

  • Create a new dict and loop over dicts, using dictionary.update() to add the key-value pairs from each one to the result.


unlisted: true

Converts miles to kilometers.

  • Follows the conversion formula km = mi * 1.609344.



Returns the minimum value of a list, after mapping each element to a value using the provided function.

  • Use map() with fn to map each element to a value using the provided function.

  • Use min() to return the minimum value.



Returns the index of the element with the minimum value in a list.

  • Use min() and list.index() to obtain the minimum value in the list and then return its index.



Returns the n minimum elements from the provided list.

  • Use sorted() to sort the list.

  • Use slice notation to get the specified number of elements.

  • Omit the second argument, n, to get a one-element list.

  • If n is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).



Calculates the month difference between two dates.

  • Subtract start from end and use datetime.timedelta.days to get the day difference.

  • Divide by 30 and use math.ceil() to get the difference in months (rounded up).



Returns the most frequent element in a list.

  • Use set() to get the unique values in lst.

  • Use max() to find the element that has the most appearances.



Generates a string with the given string value repeated n number of times.

  • Repeat the string n times, using the * operator.



Checks if the provided function returns True for at least one element in the list.

  • Use all() and fn to check if fn returns False for all the elements in the list.



Maps a number from one range to another range.

  • Return num mapped between outMin-outMax from inMin-inMax.



Moves the specified amount of elements to the end of the list.

  • Use slice notation to get the two slices of the list and combine them before returning.



Pads a string on both sides with the specified character, if it's shorter than the specified length.

  • Use str.ljust() and str.rjust() to pad both sides of the given string.

  • Omit the third argument, char, to use the whitespace character as the default padding character.



Pads a given number to the specified length.

  • Use str.zfill() to pad the number to the specified length, after converting it to a string.



Checks if the given string is a palindrome.

  • Use str.lower() and re.sub() to convert to lowercase and remove non-alphanumeric characters from the given string.

  • Then, compare the new string with its reverse, using slice notation.



Converts a list of dictionaries into a list of values corresponding to the specified key.

  • Use a list comprehension and dict.get() to get the value of key for each dictionary in lst.



Returns the powerset of a given iterable.

  • Use list() to convert the given value to a list.

  • Use range() and itertools.combinations() to create a generator that returns all subsets.

  • Use itertools.chain.from_iterable() and list() to consume the generator and return a list.



Converts an angle from radians to degrees.

  • Use math.pi and the radian to degree formula to convert the angle from radians to degrees.



Reverses a list or a string.

  • Use slice notation to reverse the list or string.



Reverses a number.

  • Use str() to convert the number to a string, slice notation to reverse it and str.replace() to remove the sign.

  • Use float() to convert the result to a number and math.copysign() to copy the original sign.



Converts the values of RGB components to a hexadecimal color code.

  • Create a placeholder for a zero-padded hexadecimal value using '{:02X}' and copy it three times.

  • Use str.format() on the resulting string to replace the placeholders with the given values.



Moves the specified amount of elements to the start of the list.

  • Use slice notation to get the two slices of the list and combine them before returning.



Returns a random element from a list.

  • Use random.choice() to get a random element from lst.



Randomizes the order of the values of an list, returning a new list.



Returns a list of elements that exist in both lists.

  • Use a list comprehension on a to only keep values contained in both lists.



Converts a string to a URL-friendly slug.

  • Use str.lower() and str.strip() to normalize the input string.

  • Use re.sub() to to replace spaces, dashes and underscores with - and remove special characters.



Converts a string to snake case.

  • Use re.sub() to match all words in the string, str.lower() to lowercase them.

  • Use re.sub() to replace any - characters with spaces.

  • Finally, use str.join() to combine all words using - as the separator.



Checks if the provided function returns True for at least one element in the list.

  • Use any() in combination with map() to check if fn returns True for any element in the list.



Sorts one list based on another list containing the desired indexes.

  • Use zip() and sorted() to combine and sort the two lists, based on the values of indexes.

  • Use a list comprehension to get the first element of each pair from the result.

  • Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the third argument.



Sorts the given dictionary by key.

  • Use dict.items() to get a list of tuple pairs from d and sort it using sorted().

  • Use dict() to convert the sorted list back to a dictionary.

  • Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.



Sorts the given dictionary by value.

  • Use dict.items() to get a list of tuple pairs from d and sort it using a lambda function and sorted().

  • Use dict() to convert the sorted list back to a dictionary.

  • Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.

  • ⚠️ NOTICE: Dictionary values must be of the same type.



Splits a multiline string into a list of lines.

  • Use str.split() and '\n' to match line breaks and create a list.

  • str.splitlines() provides similar functionality to this snippet.



Flattens a list, by spreading its elements into a new list.

  • Loop over elements, use list.extend() if the element is a list, list.append() otherwise.



Calculates the sum of a list, after mapping each element to a value using the provided function.

  • Use map() with fn to map each element to a value using the provided function.

  • Use sum() to return the sum of the values.



Returns the sum of the powers of all the numbers from start to end (both inclusive).

  • Use range() in combination with a list comprehension to create a list of elements in the desired range raised to the given power.

  • Use sum() to add the values together.

  • Omit the second argument, power, to use a default power of 2.

  • Omit the third argument, start, to use a default starting value of 1.



Returns the symmetric difference between two iterables, without filtering out duplicate values.

  • Create a set from each list.

  • Use a list comprehension on each of them to only keep values not contained in the previously created set of the other.



Returns the symmetric difference between two lists, after applying the provided function to each list element of both.

  • Create a set by applying fn to each element in every list.

  • Use a list comprehension in combination with fn on each of them to only keep values not contained in the previously created set of the other.



Returns all elements in a list except for the first one.

  • Use slice notation to return the last element if the list's length is more than 1.

  • Otherwise, return the whole list.



Returns a list with n elements removed from the beginning.

  • Use slice notation to create a slice of the list with n elements taken from the beginning.



Returns a list with n elements removed from the end.

  • Use slice notation to create a slice of the list with n elements taken from the end.



Returns the binary representation of the given number.

  • Use bin() to convert a given decimal number into its binary equivalent.



Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values.

The values of the first list need to be unique and hashable.

  • Use zip() in combination with dict() to combine the values of the two lists into a dictionary.



Returns the hexadecimal representation of the given number.

  • Use hex() to convert a given decimal number into its hexadecimal equivalent.



Converts a date to its ISO-8601 representation.

  • Use datetime.datetime.isoformat() to convert the given datetime.datetime object to an ISO-8601 date.



Converts an integer to its roman numeral representation.

Accepts value between 1 and 3999 (both inclusive).

  • Create a lookup list containing tuples in the form of (roman value, integer).

  • Use a for loop to iterate over the values in lookup.

  • Use divmod() to update num with the remainder, adding the roman numeral representation to the result.



Transposes a two-dimensional list.

  • Use *lst to get the provided list as tuples.

  • Use zip() in combination with list() to create the transpose of the given two-dimensional list.



Builds a list, using an iterator function and an initial seed value.

  • The iterator function accepts one argument (seed) and must always return a list with two elements ([value, nextSeed]) or False to terminate.

  • Use a generator function, fn_generator, that uses a while loop to call the iterator function and yield the value until it returns False.

  • Use a list comprehension to return the list that is produced by the generator, using the iterator function.



Returns every element that exists in any of the two lists once.

  • Create a set with all values of a and b and convert to a list.



Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.

  • Create a set by applying fn to each element in a.

  • Use a list comprehension in combination with fn on b to only keep values not contained in the previously created set, _a.

  • Finally, create a set from the previous result and a and transform it into a list



Returns the unique elements in a given list.

  • Create a set from the list to discard duplicated values, then return a list from it.



Returns a flat list of all the values in a flat dictionary.

  • Use dict.values() to return the values in the given dictionary.

  • Return a list() of the previous result.



Returns the weighted average of two or more numbers.

  • Use sum() to sum the products of the numbers by their weight and to sum the weights.

  • Use zip() and a list comprehension to iterate over the pairs of values and weights.



Tests a value, x, against a testing function, conditionally applying a function.

  • Check if the value of predicate(x) is True and if so return when_true(x), otherwise return x.



Converts a given string into a list of words.

  • Use re.findall() with the supplied pattern to find all matching substrings.

  • Omit the second argument to use the default regexp, which matches alphanumeric and hyphens.

Last updated

Was this helpful?