Python snippets
Small Python functions for lists, dictionaries, strings, maths and dates, each with a short explanation and an example call.
Short third-party examples with no input validation or error handling, and most have no type hints. Check the standard library first (itertools, functools, collections), since many have a built-in equivalent. See Python for project and tooling guidance.
- Add days to dateCalculates the date of n days from the given date.
- All indexes of valueReturns a list of indexes of all the occurrences of an element in a list.
- Apply function when trueTests a value, x, against a testing function, conditionally applying a function.
- Arithmetic progressionGenerates a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit.
- AverageCalculates the average of two or more numbers.
- Bifurcate list based on functionSplits values into two groups, based on the result of the given filtering function.
- Bifurcate list based on valuesSplits values into two groups, based on the result of the given filter list.
- Binomial coefficientCalculates the number of ways to choose k items from n items without repetition and without order.
- Byte size of stringReturns the length of a string in bytes.
- Camelcase stringConverts a string to camelcase.
- Capitalize every wordCapitalizes the first letter of every word in a string.
- Capitalize stringCapitalizes the first letter of a string.
- Cast to listCasts the provided value as a list if it’s not one.
- Celsius to FahrenheitConverts Celsius to Fahrenheit.
- Check for duplicates in listChecks if there are duplicate values in a flat list.
- Check if list elements are identicalChecks if all elements in a list are equal.
- Check if list has no duplicatesChecks if all the values in a list are unique.
- Check lists have same contentsChecks if two lists contain the same elements regardless of order.
- Check propertyCreates a function that will invoke a predicate function for the specified property on a given dictionary.
- Clamp numberClamps num within the inclusive range specified by the boundary values.
- Combine dictionary valuesCombines two or more dictionaries, creating a list of values for each key.
- Compact listRemoves falsy values from a list.
- Compose functionsPerforms right-to-left function composition.
- Count grouped elementsGroups the elements of a list based on the given function and returns the count of elements in each group.
- Count occurrencesCounts the occurrences of a value in a list.
- Curry functionCurries a function.
- Date difference in daysCalculates the day difference between two dates.
- Date difference in monthsCalculates the month difference between two dates.
- Date from ISO formatConverts a date from its ISO-8601 representation.
- Date is weekdayChecks if the given date is a weekday.
- Date is weekendChecks if the given date is a weekend.
- Date rangeCreates a list of dates between start (inclusive) and end (not inclusive).
- Date to ISO formatConverts a date to its ISO-8601 representation.
- Days agoCalculates the date of n days ago from today.
- Days from nowCalculates the date of n days from today.
- Decapitalize stringDecapitalizes the first letter of a string.
- Deep flatten listDeep flattens a list.
- Degrees to radiansConverts an angle from degrees to radians.
- Delayed function executionInvokes the provided function after ms milliseconds.
- Dictionary keysCreates a flat list of all the keys in a flat dictionary.
- Dictionary to listConverts a dictionary to a list of tuples.
- Dictionary valuesReturns a flat list of all the values in a flat dictionary.
- Digitize numberConverts a number to a list of digits.
- Drop list elements from the leftReturns a list with n elements removed from the left.
- Drop list elements from the rightReturns a list with n elements removed from the right.
- Every nth element in listReturns every nth element in a list.
- Execute function for each list elementExecutes the provided function once for each list element.
- Execute function for each list element in reverseExecutes the provided function once for each list element, starting from the list’s last element.
- FactorialCalculates the factorial of a number.
- Fahrenheit to CelsiusConverts Fahrenheit to Celsius.
- FibonacciGenerates a list, containing the Fibonacci sequence, up until the nth term.
- Filter non-unique list valuesCreates a list with the non-unique values filtered out.
- Filter unique list valuesCreates a list with the unique values filtered out.
- Find all matching indexesFinds the indexes of all elements in the given list that satisfy the provided testing function.
- Find key of valueFinds the first key in the provided dictionary that has the given value.
- Find keys with valueFinds all keys in the provided dictionary that have the given value.
- Find last matching indexFinds the index of the last element in the given list that satisfies the provided testing function.
- Find last matching valueFinds the value of the last element in the given list that satisfies the provided testing function.
- Find matching indexFinds the index of the first element in the given list that satisfies the provided testing function.
- Find matching valueFinds the value of the first element in the given list that satisfies the provided testing function.
- Find parity outliersFinds the items that are parity outliers in a given list.
- Flatten listFlattens a list of lists once.
- Geometric progressionInitializes a list containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step.
- Get nested valueRetrieves the value of the nested key indicated by the given selector list from a dictionary or list.
- Greatest common divisorCalculates the greatest common divisor of a list of numbers.
- Group list elementsGroups the elements of a list based on the given function.
- Hamming distanceCalculates the Hamming distance between two values.
- Hex to RGBConverts a hexadecimal color code to a tuple of integers corresponding to its RGB components.
- Index of max elementReturns the index of the element with the maximum value in a list.
- Index of min elementReturns the index of the element with the minimum value in a list.
- Initialize 2D listInitializes a 2D list of given width and height and value.
- Initialize list with rangeInitializes a list containing the numbers in the specified range where start and end are inclusive with their common difference step.
- Initialize list with valuesInitializes and fills a list with the specified value.
- Integer to roman numeralConverts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).
- Invert dictionaryInverts a dictionary with non-unique hashable values.
- Invert dictionaryInverts a dictionary with unique hashable values.
- Kebabcase stringConverts a string to kebab case.
- Key in dictionaryChecks if the given key exists in a dictionary.
- Key of max valueFinds the key of the maximum value in a dictionary.
- Key of min valueFinds the key of the minimum value in a dictionary.
- Km to milesConverts kilometers to miles.
- Last list elementReturns the last element in a list.
- Least common multipleReturns the least common multiple of a list of numbers.
- List differenceCalculates the difference between two iterables, without filtering duplicate values.
- List difference based on functionReturns the difference between two lists, after applying the provided function to each list element of both.
- List headReturns the head of a list.
- List includes all valuesChecks if all the elements in values are included in lst.
- List includes any valuesChecks if any element in values is included in lst.
- List intersectionReturns a list of elements that exist in both lists.
- List intersection based on functionReturns a list of elements that exist in both lists, after applying the provided function to each list element of both.
- List is contained in other listChecks if the elements of the first list are contained in the second one regardless of order.
- List similarityReturns a list of elements that exist in both lists.
- List symmetric differenceReturns the symmetric difference between two iterables, without filtering out duplicate values.
- List symmetric difference based on functionReturns the symmetric difference between two lists, after applying the provided function to each list element of both.
- List tailReturns all elements in a list except for the first one.
- List unionReturns every element that exists in any of the two lists once.
- List union based on functionReturns every element that exists in any of the two lists once, after applying the provided function to each element of both.
- List without last elementReturns all the elements of a list except the last one.
- Lists to dictionaryCombines 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.
- Longest itemTakes any number of iterable objects or objects with a length property and returns the longest one.
- Map dictionary valuesCreates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.
- Map list to dictionaryMaps 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.
- Map number to rangeMaps a number from one range to another range.
- Mapped list averageCalculates the average of a list, after mapping each element to a value using the provided function.
- Max list value based on functionReturns the maximum value of a list, after mapping each element to a value using the provided function.
- MedianFinds the median of a list of numbers.
- Merge dictionariesMerges two or more dictionaries.
- Merge listsMerges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.
- Miles to kmConverts miles to kilometers.
- Min list value based on functionReturns the minimum value of a list, after mapping each element to a value using the provided function.
- Most frequent elementReturns the most frequent element in a list.
- N max elementsReturns the n maximum elements from the provided list.
- N min elementsReturns the n minimum elements from the provided list.
- Number in rangeChecks if the given number falls within the given range.
- Number is divisibleChecks if the first numeric argument is divisible by the second one.
- Number is evenChecks if the given number is even.
- Number is oddChecks if the given number is odd.
- Number is primeChecks if the provided integer is a prime number.
- Number to binaryReturns the binary representation of the given number.
- Number to hexReturns the hexadecimal representation of the given number.
- Offset list elementsMoves the specified amount of elements to the end of the list.
- Pad numberPads a given number to the specified length.
- Pad stringPads a string on both sides with the specified character, if it’s shorter than the specified length.
- PalindromeChecks if the given string is a palindrome.
- Partial sum listCreates a list of partial sums.
- Pluck values from list of dictionariesConverts a list of dictionaries into a list of values corresponding to the specified key.
- PowersetReturns the powerset of a given iterable.
- Radians to degreesConverts an angle from radians to degrees.
- Random element in listReturns a random element from a list.
- Remove list elementsReturns a list with n elements removed from the beginning.
- Remove list elements from the endReturns a list with n elements removed from the end.
- Repeat stringGenerates a string with the given string value repeated n number of times.
- Reverse compose functionsPerforms left-to-right function composition.
- Reverse listReverses a list or a string.
- Reverse numberReverses a number.
- RGB to hexConverts the values of RGB components to a hexadecimal color code.
- Rotate list elementsMoves the specified amount of elements to the start of the list.
- Shuffle listRandomizes the order of the values of an list, returning a new list.
- Snakecase stringConverts a string to snake case.
- Sort dictionary by keySorts the given dictionary by key.
- Sort dictionary by valueSorts the given dictionary by value.
- Sort list by indexesSorts one list based on another list containing the desired indexes.
- Split into linesSplits a multiline string into a list of lines.
- Split list into chunksChunks a list into smaller lists of a specified size.
- Split list into n chunksChunks a list into n smaller lists.
- Spread listFlattens a list, by spreading its elements into a new list.
- String is anagramChecks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
- String to slugConverts a string to a URL-friendly slug.
- String to wordsConverts a given string into a list of words.
- Sum list based on functionCalculates the sum of a list, after mapping each element to a value using the provided function.
- Sum of powersReturns the sum of the powers of all the numbers from start to end (both inclusive).
- Test if every list element is falsyChecks if the provided function returns True for at least one element in the list.
- Test if every list element is truthyChecks if the provided function returns True for every element in the list.
- Test if some list elements are truthyChecks if the provided function returns True for at least one element in the list.
- Transpose matrixTransposes a two-dimensional list.
- Unfold listBuilds a list, using an iterator function and an initial seed value.
- Unique elements in listReturns the unique elements in a given list.
- Value frequenciesCreates a dictionary with the unique values of a list as keys and their frequencies as the values.
- Weighted averageReturns the weighted average of two or more numbers.
No snippet matches that filter.