Snippets
Python snippets
Small, self-contained Python functions. Each one shows the implementation, a short explanation of how it works and an example call.
- Add days to date Calculates the date of n days from the given date. Use datetime.timedelta and the + operator to calculate the …
- All indexes of value Returns a list of indexes of all the occurrences of an element in a list. Use enumerate() and a list …
- Apply function when true Tests a value, x, against a testing function, conditionally applying a function. Check if the value of …
- Arithmetic progression Generates a list of numbers in the arithmetic progression starting with the given positive integer and up to …
- Average Calculates the average of two or more numbers. Use sum() to sum all of the args provided, divide by len(). def …
- Bifurcate list based on function Splits values into two groups, based on the result of the given filtering function. Use a list comprehension …
- Bifurcate list based on values Splits values into two groups, based on the result of the given filter list. Use a list comprehension and …
- Binomial coefficient Calculates the number of ways to choose k items from n items without repetition and without order. Use …
- Byte size of string Returns the length of a string in bytes. Use str.encode() to encode the given string and return its length. …
- Camelcase string Converts a string to camelcase. Use re.sub() to replace any - or _ with a space, using the regexp …
- Capitalize every word Capitalizes the first letter of every word in a string. Use str.title() to capitalize the first letter of …
- Capitalize string Capitalizes the first letter of a string. Use list slicing and str.upper() to capitalize the first letter of …
- Cast to list Casts the provided value as a list if it’s not one. Use isinstance() to check if the given value is …
- Celsius to Fahrenheit Converts Celsius to Fahrenheit. Follow the conversion formula F = 1.8 * C + 32. def …
- Check for duplicates in list Checks if there are duplicate values in a flat list. Use set() on the given list to remove duplicates, compare …
- Check if list elements are identical Checks if all elements in a list are equal. Use set() to eliminate duplicate elements and then use len() to …
- Check if list has no duplicates Checks if all the values in a list are unique. Use set() on the given list to keep only unique occurrences. …
- Check lists have same contents Checks if two lists contain the same elements regardless of order. Use set() on the combination of both lists …
- Check property Creates a function that will invoke a predicate function for the specified property on a given dictionary. …
- Clamp number Clamps num within the inclusive range specified by the boundary values. If num falls within the range (a, b), …
- Combine dictionary values Combines two or more dictionaries, creating a list of values for each key. Create a new …
- Compact list Removes falsy values from a list. Use filter() to filter out falsy values (False, None, 0, and ""). …
- Compose functions Performs right-to-left function composition. Use functools.reduce() to perform right-to-left function …
- Count grouped elements Groups the elements of a list based on the given function and returns the count of elements in each group. Use …
- Count occurrences Counts the occurrences of a value in a list. Use list.count() to count the number of occurrences of val in …
- Curry function Curries a function. Use functools.partial() to return a new partial object which behaves like fn with the …
- Date difference in days Calculates the day difference between two dates. Subtract start from end and use datetime.timedelta.days to …
- Date difference in months Calculates the month difference between two dates. Subtract start from end and use datetime.timedelta.days to …
- Date from ISO format Converts a date from its ISO-8601 representation. Use datetime.datetime.fromisoformat() to convert the given …
- Date is weekday Checks if the given date is a weekday. Use datetime.datetime.weekday() to get the day of the week as an …
- Date is weekend Checks if the given date is a weekend. Use datetime.datetime.weekday() to get the day of the week as an …
- Date range Creates a list of dates between start (inclusive) and end (not inclusive). Use datetime.timedelta.days to get …
- Date to ISO format Converts a date to its ISO-8601 representation. Use datetime.datetime.isoformat() to convert the given …
- Days ago Calculates the date of n days ago from today. Use datetime.date.today() to get the current day. Use …
- Days from now Calculates the date of n days from today. Use datetime.date.today() to get the current day. Use …
- Decapitalize string Decapitalizes the first letter of a string. Use list slicing and str.lower() to decapitalize the first letter …
- Deep flatten list Deep flattens a list. Use recursion. Use isinstance() with collections.abc.Iterable to check if an element is …
- Degrees to radians Converts an angle from degrees to radians. Use math.pi and the degrees to radians formula to convert the angle …
- Delayed function execution Invokes the provided function after ms milliseconds. Use time.sleep() to delay the execution of fn by ms / …
- Dictionary keys Creates a flat list of all the keys in a flat dictionary. Use dict.keys() to return the keys in the given …
- Dictionary to list Converts a dictionary to a list of tuples. Use dict.items() and list() to get a list of tuples from the given …
- Dictionary values Returns a flat list of all the values in a flat dictionary. Use dict.values() to return the values in the …
- Digitize number Converts a number to a list of digits. Use map() combined with int on the string representation of n and …
- Drop list elements from the left Returns a list with n elements removed from the left. Use slice notation to remove the specified number of …
- Drop list elements from the right Returns a list with n elements removed from the right. Use slice notation to remove the specified number of …
- Every nth element in list Returns every nth element in a list. Use slice notation to create a new list that contains every nth element …
- Execute function for each list element Executes the provided function once for each list element. Use a for loop to execute fn for each element in …
- Execute function for each list element in reverse Executes the provided function once for each list element, starting from the list’s last element. Use a …
- Factorial Calculates the factorial of a number. Use recursion. If num is less than or equal to 1, return 1. Otherwise, …
- Fahrenheit to Celsius Converts Fahrenheit to Celsius. Follow the conversion formula C = (F - 32) * 5 / 9. def …
- Fibonacci Generates a list, containing the Fibonacci sequence, up until the nth term. Starting with 0 and 1, use …
- Filter non-unique list values Creates a list with the non-unique values filtered out. Use collections.Counter to get the count of each value …
- Filter unique list values Creates a list with the unique values filtered out. Use collections.Counter to get the count of each value in …
- Find all matching indexes Finds the indexes of all elements in the given list that satisfy the provided testing function. Use …
- Find key of value Finds the first key in the provided dictionary that has the given value. Use dictionary.items() and next() to …
- Find keys with value Finds all keys in the provided dictionary that have the given value. Use dictionary.items(), a generator and …
- Find last matching index Finds the index of the last element in the given list that satisfies the provided testing function. Use a list …
- Find last matching value Finds the value of the last element in the given list that satisfies the provided testing function. Use a list …
- Find matching index Finds the index of the first element in the given list that satisfies the provided testing function. Use a …
- Find matching value Finds the value of the first element in the given list that satisfies the provided testing function. Use a …
- Find parity outliers Finds the items that are parity outliers in a given list. Use collections.Counter with a list comprehension to …
- Flatten list Flattens a list of lists once. Use a list comprehension to extract each value from sub-lists in order. def …
- Geometric progression Initializes a list containing the numbers in the specified range where start and end are inclusive and the …
- Get nested value Retrieves the value of the nested key indicated by the given selector list from a dictionary or list. Use …
- Greatest common divisor Calculates the greatest common divisor of a list of numbers. Use functools.reduce() and math.gcd() over the …
- Group list elements Groups the elements of a list based on the given function. Use collections.defaultdict to initialize a …
- Hamming distance Calculates the Hamming distance between two values. Use the XOR operator (^) to find the bit difference …
- Hex to RGB Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components. Use a list …
- Index of max element Returns the index of the element with the maximum value in a list. Use max() and list.index() to get the …
- Index of min element Returns the index of the element with the minimum value in a list. Use min() and list.index() to obtain the …
- Initialize 2D list Initializes a 2D list of given width and height and value. Use a list comprehension and range() to generate h …
- Initialize list with range Initializes a list containing the numbers in the specified range where start and end are inclusive with their …
- Initialize list with values Initializes and fills a list with the specified value. Use a list comprehension and range() to generate a list …
- Integer to roman numeral Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive). …
- Invert dictionary Inverts a dictionary with non-unique hashable values. Create a collections.defaultdict with list as the …
- Invert dictionary Inverts a dictionary with unique hashable values. Use dictionary.items() in combination with a list …
- Kebabcase string Converts a string to kebab case. Use re.sub() to replace any - or _ with a space, using the regexp …
- Key in dictionary Checks if the given key exists in a dictionary. Use the in operator to check if d contains key. def …
- Key of max value Finds the key of the maximum value in a dictionary. Use max() with the key parameter set to dict.get() to find …
- Key of min value Finds the key of the minimum value in a dictionary. Use min() with the key parameter set to dict.get() to find …
- Km to miles Converts kilometers to miles. Follows the conversion formula mi = km * 0.621371. def km_to_miles(km): return …
- Last list element Returns the last element in a list. Use lst[-1] to return the last element of the passed list. def last(lst): …
- Least common multiple Returns the least common multiple of a list of numbers. Use functools.reduce(), math.gcd() and lcm(x, y) = x * …
- List difference Calculates the difference between two iterables, without filtering duplicate values. Create a set from b. Use …
- List difference based on function Returns the difference between two lists, after applying the provided function to each list element of both. …
- List head Returns the head of a list. Use lst[0] to return the first element of the passed list. def head(lst): return …
- List includes all values Checks if all the elements in values are included in lst. Check if every value in values is contained in lst …
- List includes any values Checks if any element in values is included in lst. Check if any value in values is contained in lst using a …
- List intersection Returns a list of elements that exist in both lists. Create a set from a and b. Use the built-in set operator …
- List intersection based on function Returns a list of elements that exist in both lists, after applying the provided function to each list element …
- List is contained in other list Checks if the elements of the first list are contained in the second one regardless of order. Use count() to …
- List similarity Returns a list of elements that exist in both lists. Use a list comprehension on a to only keep values …
- List symmetric difference Returns the symmetric difference between two iterables, without filtering out duplicate values. Create a set …
- List symmetric difference based on function Returns the symmetric difference between two lists, after applying the provided function to each list element …
- List tail Returns all elements in a list except for the first one. Use slice notation to return the last element if the …
- List union Returns every element that exists in any of the two lists once. Create a set with all values of a and b and …
- List union based on function Returns every element that exists in any of the two lists once, after applying the provided function to each …
- List without last element Returns all the elements of a list except the last one. Use lst[:-1] to return all but the last element of the …
- Lists to dictionary Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements …
- Longest item Takes any number of iterable objects or objects with a length property and returns the longest one. Use max() …
- Map dictionary values Creates a dictionary with the same keys as the provided dictionary and values generated by running the …
- Map list to dictionary Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original …
- Map number to range Maps a number from one range to another range. Return num mapped between outMin-outMax from inMin-inMax. def …
- Mapped list average Calculates the average of a list, after mapping each element to a value using the provided function. Use map() …
- Max list value based on function Returns the maximum value of a list, after mapping each element to a value using the provided function. Use …
- Median Finds the median of a list of numbers. Sort the numbers of the list using list.sort(). Find the median, which …
- Merge dictionaries Merges two or more dictionaries. Create a new dict and loop over dicts, using dictionary.update() to add the …
- Merge lists Merges two or more lists into a list of lists, combining elements from each of the input lists based on their …
- Miles to km Converts miles to kilometers. Follows the conversion formula km = mi * 1.609344. def miles_to_km(miles): …
- Min list value based on function Returns the minimum value of a list, after mapping each element to a value using the provided function. Use …
- Most frequent element Returns the most frequent element in a list. Use set() to get the unique values in lst. Use max() to find the …
- N max elements Returns the n maximum elements from the provided list. Use sorted() to sort the list. Use slice notation to …
- N min elements Returns the n minimum elements from the provided list. Use sorted() to sort the list. Use slice notation to …
- Number in range Checks if the given number falls within the given range. Use arithmetic comparison to check if the given …
- Number is divisible Checks if the first numeric argument is divisible by the second one. Use the modulo operator (%) to check if …
- Number is even Checks if the given number is even. Check whether a number is odd or even using the modulo (%) operator. …
- Number is odd Checks if the given number is odd. Checks whether a number is even or odd using the modulo (%) operator. …
- Number is prime Checks if the provided integer is a prime number. Return False if the number is 0, 1, a negative number or a …
- Number to binary Returns the binary representation of the given number. Use bin() to convert a given decimal number into its …
- Number to hex Returns the hexadecimal representation of the given number. Use hex() to convert a given decimal number into …
- Offset list elements Moves the specified amount of elements to the end of the list. Use slice notation to get the two slices of the …
- Pad number Pads a given number to the specified length. Use str.zfill() to pad the number to the specified length, after …
- Pad string Pads a string on both sides with the specified character, if it’s shorter than the specified length. Use …
- Palindrome Checks if the given string is a palindrome. Use str.lower() and re.sub() to convert to lowercase and remove …
- Partial sum list Creates a list of partial sums. Use itertools.accumulate() to create the accumulated sum for each element. Use …
- Pluck values from list of dictionaries Converts a list of dictionaries into a list of values corresponding to the specified key. Use a list …
- Powerset Returns the powerset of a given iterable. Use list() to convert the given value to a list. Use range() and …
- Radians to degrees Converts an angle from radians to degrees. Use math.pi and the radian to degree formula to convert the angle …
- Random element in list Returns a random element from a list. Use random.choice() to get a random element from lst. from random import …
- Remove list elements Returns a list with n elements removed from the beginning. Use slice notation to create a slice of the list …
- Remove list elements from the end Returns a list with n elements removed from the end. Use slice notation to create a slice of the list with n …
- Repeat string Generates a string with the given string value repeated n number of times. Repeat the string n times, using …
- Reverse compose functions Performs left-to-right function composition. Use functools.reduce() to perform left-to-right function …
- Reverse list Reverses a list or a string. Use slice notation to reverse the list or string. def reverse(itr): return …
- Reverse number Reverses a number. Use str() to convert the number to a string, slice notation to reverse it and str.replace() …
- RGB to hex Converts the values of RGB components to a hexadecimal color code. Create a placeholder for a zero-padded …
- Rotate list elements Moves the specified amount of elements to the start of the list. Use slice notation to get the two slices of …
- Shuffle list Randomizes the order of the values of an list, returning a new list. Uses the Fisher-Yates algorithm to …
- Snakecase string Converts a string to snake case. Use re.sub() to match all words in the string, str.lower() to lowercase them. …
- Sort dictionary by key Sorts the given dictionary by key. Use dict.items() to get a list of tuple pairs from d and sort it using …
- Sort dictionary by value Sorts the given dictionary by value. Use dict.items() to get a list of tuple pairs from d and sort it using a …
- Sort list by indexes Sorts one list based on another list containing the desired indexes. Use zip() and sorted() to combine and …
- Split into lines Splits a multiline string into a list of lines. Use str.split() and '\n' to match line breaks and create a …
- Split list into chunks Chunks a list into smaller lists of a specified size. Use list() and range() to create a list of the desired …
- Split list into n chunks Chunks a list into n smaller lists. Use math.ceil() and len() to get the size of each chunk. Use list() and …
- Spread list Flattens a list, by spreading its elements into a new list. Loop over elements, use list.extend() if the …
- String is anagram Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special …
- String to slug Converts a string to a URL-friendly slug. Use str.lower() and str.strip() to normalize the input string. Use …
- String to words Converts a given string into a list of words. Use re.findall() with the supplied pattern to find all matching …
- Sum list based on function Calculates the sum of a list, after mapping each element to a value using the provided function. Use map() …
- Sum of powers Returns the sum of the powers of all the numbers from start to end (both inclusive). Use range() in …
- Test if every list element is falsy Checks if the provided function returns True for at least one element in the list. Use all() and fn to check …
- Test if every list element is truthy Checks if the provided function returns True for every element in the list. Use all() in combination with …
- Test if some list elements are truthy Checks if the provided function returns True for at least one element in the list. Use any() in combination …
- Transpose matrix Transposes a two-dimensional list. Use *lst to get the provided list as tuples. Use zip() in combination with …
- Unfold list Builds a list, using an iterator function and an initial seed value. The iterator function accepts one …
- Unique elements in list Returns the unique elements in a given list. Create a set from the list to discard duplicated values, then …
- Value frequencies Creates a dictionary with the unique values of a list as keys and their frequencies as the values. Use …
- Weighted average Returns the weighted average of two or more numbers. Use sum() to sum the products of the numbers by their …
No snippet matches that filter.