Python Snippets
Calculates the date of n days from the given date.
n days from the given date.Use
datetime.timedeltaand the+operator to calculate the newdatetime.datetimevalue after addingndays tod.Omit the second argument,
d, to use a default value ofdatetime.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 uselen()to check if length is1.
def all_equal(lst):
return len(set(lst)) == 1Checks 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()andlist()with the appropriate start, step and end values.
Calculates the average of two or more numbers.
Use
sum()to sum all of theargsprovided, divide bylen().
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 byfn.Use
sum()to sum all of the mapped values, divide bylen(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.
filter list.Use a list comprehension and
zip()to add elements to groups, based onfilter.If
filterhas 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
fnfor each element.If
fnreturns 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.
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 regexpr"(_|-)+".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_restparameter to keep the rest of the string intact, or set it toTrueto 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
lambdafunction that takes an object and applies the predicate function,fnto the specified property.
Chunks a list into smaller lists of a specified size.
Use
list()andrange()to create a list of the desiredsize.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.
n smaller lists.Use
math.ceil()andlen()to get the size of each chunk.Use
list()andrange()to create a new list of sizen.Use
map()to map each element of the new list to a chunk the length ofsize.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.
num within the inclusive range specified by the boundary values.If
numfalls within the range (a,b), returnnum.Otherwise, return the nearest number in the range.
Inverts a dictionary with non-unique hashable values.
Create a
collections.defaultdictwithlistas the default value for each key.Use
dictionary.items()in combination with a loop to map the values of the dictionary to keys usingdict.append().Use
dict()to convert thecollections.defaultdictto a regular dictionary.
Combines two or more dictionaries, creating a list of values for each key.
Create a new
collections.defaultdictwithlistas the default value for each key and loop overdicts.Use
dict.append()to map the values of the dictionary to keys.Use
dict()to convert thecollections.defaultdictto 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.defaultdictto 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 ofvalinlst.
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 likefnwith the given arguments,args, partially applied.
Creates a list of dates between start (inclusive) and end (not inclusive).
start (inclusive) and end (not inclusive).Use
datetime.timedelta.daysto get the days betweenstartandend.Use
int()to convert the result to an integer andrange()to iterate over each day.Use a list comprehension and
datetime.timedelta()to create a list ofdatetime.dateobjects.
Calculates the date of n days ago from today.
n days ago from today.Use
datetime.date.today()to get the current day.Use
datetime.timedeltato subtractndays from today's date.
Calculates the day difference between two dates.
Subtract
startfromendand usedatetime.timedelta.daysto get the day difference.
Calculates the date of n days from today.
n days from today.Use
datetime.date.today()to get the current day.Use
datetime.timedeltato addndays 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_restparameter to keep the rest of the string intact, or set it toTrueto convert to uppercase.
Deep flattens a list.
Use recursion.
Use
isinstance()withcollections.abc.Iterableto 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.piand the degrees to radians formula to convert the angle from degrees to radians.
Invokes the provided function after ms milliseconds.
ms milliseconds.Use
time.sleep()to delay the execution offnbyms / 1000seconds.
Converts a dictionary to a list of tuples.
Use
dict.items()andlist()to get a list of tuples from the given dictionary.
Calculates the difference between two iterables, without filtering duplicate values.
Create a
setfromb.Use a list comprehension on
ato 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, usingmap()to applyfnto each element inb.Use a list comprehension in combination with
fnonato only keep values not contained in the previously created set,_b.
Converts a number to a list of digits.
Use
map()combined withinton the string representation ofnand return a list from the result.
Returns a list with n elements removed from the left.
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 of1.
Returns a list with n elements removed from the right.
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 of1.
Checks if the provided function returns True for every element in the list.
True for every element in the list.Use
all()in combination withmap()andfnto check iffnreturnsTruefor all elements in the list.
Returns every nth element in a list.
nth element in a list.Use slice notation to create a new list that contains every
nthelement of the given list.
Calculates the factorial of a number.
Use recursion.
If
numis less than or equal to1, return1.Otherwise, return the product of
numand the factorial ofnum - 1.Throws an exception if
numis 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
0and1, uselist.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 reachesn.If
nis less or equal to0, return a list containing0.
Creates a list with the non-unique values filtered out.
Use
collections.Counterto 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.Counterto 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 inlstfor whichfnreturnsTrue.
Finds the index of the first element in the given list that satisfies the provided testing function.
Use a list comprehension,
enumerate()andnext()to return the index of the first element inlstfor whichfnreturnsTrue.
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 inlstfor whichfnreturnsTrue.
Finds the first key in the provided dictionary that has the given value.
Use
dictionary.items()andnext()to return the first key that has a value equal toval.
Finds all keys in the provided dictionary that have the given value.
Use
dictionary.items(), a generator andlist()to return all keys that have a value equal toval.
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 inlstfor whichfnreturnsTrue.
Finds the index of the last element in the given list that satisfies the provided testing function.
Use a list comprehension,
enumerate()andnext()to return the index of the last element inlstfor whichfnreturnsTrue.
Finds the items that are parity outliers in a given list.
Use
collections.Counterwith 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
forloop to executefnfor each element initr.
Executes the provided function once for each list element, starting from the list's last element.
Use a
forloop in combination with slice notation to executefnfor each element initr, 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 adatetime.datetimeobject.
Calculates the greatest common divisor of a list of numbers.
Use
functools.reduce()andmath.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.
start and end are inclusive and the ratio between two terms is step.Returns an error if step equals 1.
Use
range(),math.log()andmath.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 of1.Omit the third argument,
step, to use a default value of2.
Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.
Use
functools.reduce()to iterate over theselectorslist.Apply
operator.getitem()for each key inselectors, 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.defaultdictto initialize a dictionary.Use
fnin combination with aforloop anddict.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()ofstrclass to count and return the number of1s 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
forloop comparing thecount()of each unique value in each list.Return
Falseif the counts do not match for any element,Trueotherwise.
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 from0tostart.
Checks if all the elements in values are included in lst.
values are included in lst.Check if every value in
valuesis contained inlstusing aforloop.Return
Falseif any one value is not found,Trueotherwise.
Checks if any element in values is included in lst.
values is included in lst.Check if any value in
valuesis contained inlstusing aforloop.Return
Trueif any one value is found,Falseotherwise.
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 withvalueand addingito 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 generatehrows where each is a list with lengthh, initialized withval.Omit the last argument,
val, to set the default value toNone.
Initializes a list containing the numbers in the specified range where start and end are inclusive with their common difference step.
start and end are inclusive with their common difference step.Use
list()andrange()to generate a list of the appropriate length, filled with the desired values in the given range.Omit
startto use the default value of0.Omit
stepto use the default value of1.
Initializes and fills a list with the specified value.
Use a list comprehension and
range()to generate a list of length equal ton, filled with the desired values.Omit
valto use the default value of0.
Returns a list of elements that exist in both lists.
Create a
setfromaandb.Use the built-in set operator
&to only keep values contained in both sets, then transform thesetback into alist.
Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.
Create a
set, usingmap()to applyfnto each element inb.Use a list comprehension in combination with
fnonato 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.Counterto 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 inahas more occurrences than it has inb.Return
Falseif any such value is found,Trueotherwise.
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 to0.
unlisted: true
Checks if the given number is even.
Check whether a number is odd or even using the modulo (
%) operator.Return
Trueif the number is even,Falseif 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
Trueif the number is odd,Falseif the number is even.
Checks if the provided integer is a prime number.
Return
Falseif the number is0,1, a negative number or a multiple of2.Use
all()andrange()to check numbers from3to the square root of the given number.Return
Trueif none divides the given number,Falseotherwise.
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 ofdatetime.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 ofdatetime.today().
Converts a string to kebab case.
Use
re.sub()to replace any-or_with a space, using the regexpr"(_|-)+".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
inoperator to check ifdcontainskey.
Finds the key of the maximum value in a dictionary.
Use
max()with thekeyparameter set todict.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 thekeyparameter set todict.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()andlcm(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()withlen()as thekeyto 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 applyfnto each value of the list.Use
zip()to pair original values to the values produced byfn.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 byfnto 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()withfnto 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()andlist.index()to get the maximum value in the list and return its index.
Returns the n maximum elements from the provided list.
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
nis 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 themax_lengthvariable to loop as many times as there are elements in the longest list.If a list is shorter than
max_length, usefill_valuefor the remaining items (defaults toNone).zip()anditertools.zip_longest()provide similar functionality to this snippet.
Merges two or more dictionaries.
Create a new
dictand loop overdicts, usingdictionary.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()withfnto 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()andlist.index()to obtain the minimum value in the list and then return its index.
Returns the n minimum elements from the provided list.
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
nis 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
startfromendand usedatetime.timedelta.daysto get the day difference.Divide by
30and usemath.ceil()to get the difference in months (rounded up).
Returns the most frequent element in a list.
Use
set()to get the unique values inlst.Use
max()to find the element that has the most appearances.
Generates a string with the given string value repeated n number of times.
n number of times.Repeat the string
ntimes, using the*operator.
Checks if the provided function returns True for at least one element in the list.
True for at least one element in the list.Use
all()andfnto check iffnreturnsFalsefor all the elements in the list.
Maps a number from one range to another range.
Return
nummapped betweenoutMin-outMaxfrominMin-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()andstr.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()andre.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.
key.Use a list comprehension and
dict.get()to get the value ofkeyfor each dictionary inlst.
Returns the powerset of a given iterable.
Use
list()to convert the given value to a list.Use
range()anditertools.combinations()to create a generator that returns all subsets.Use
itertools.chain.from_iterable()andlist()to consume the generator and return a list.
Converts an angle from radians to degrees.
Use
math.piand 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 andstr.replace()to remove the sign.Use
float()to convert the result to a number andmath.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 fromlst.
Randomizes the order of the values of an list, returning a new list.
Uses the Fisher-Yates algorithm to reorder the elements of the list.
random.shuffleprovides similar functionality to this snippet.
Returns a list of elements that exist in both lists.
Use a list comprehension on
ato only keep values contained in both lists.
Converts a string to a URL-friendly slug.
Use
str.lower()andstr.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.
True for at least one element in the list.Use
any()in combination withmap()to check iffnreturnsTruefor any element in the list.
Sorts one list based on another list containing the desired indexes.
Use
zip()andsorted()to combine and sort the two lists, based on the values ofindexes.Use a list comprehension to get the first element of each pair from the result.
Use the
reverseparameter insorted()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 fromdand sort it usingsorted().Use
dict()to convert the sorted list back to a dictionary.Use the
reverseparameter insorted()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 fromdand sort it using a lambda function andsorted().Use
dict()to convert the sorted list back to a dictionary.Use the
reverseparameter insorted()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()withfnto 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).
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 givenpower.Use
sum()to add the values together.Omit the second argument,
power, to use a default power of2.Omit the third argument,
start, to use a default starting value of1.
Returns the symmetric difference between two iterables, without filtering out duplicate values.
Create a
setfrom 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
setby applyingfnto each element in every list.Use a list comprehension in combination with
fnon 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.
n elements removed from the beginning.Use slice notation to create a slice of the list with
nelements taken from the beginning.
Returns a list with n elements removed from the end.
n elements removed from the end.Use slice notation to create a slice of the list with
nelements 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 withdict()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 givendatetime.datetimeobject 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
forloop to iterate over the values inlookup.Use
divmod()to updatenumwith the remainder, adding the roman numeral representation to the result.
Transposes a two-dimensional list.
Use
*lstto get the provided list as tuples.Use
zip()in combination withlist()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]) orFalseto terminate.Use a generator function,
fn_generator, that uses awhileloop to call the iterator function andyieldthevalueuntil it returnsFalse.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
setwith all values ofaandband convert to alist.
Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.
Create a
setby applyingfnto each element ina.Use a list comprehension in combination with
fnonbto only keep values not contained in the previously created set,_a.Finally, create a
setfrom the previous result andaand transform it into alist
Returns the unique elements in a given list.
Create a
setfrom the list to discard duplicated values, then return alistfrom 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.
x, against a testing function, conditionally applying a function.Check if the value of
predicate(x)isTrueand if so returnwhen_true(x), otherwise returnx.
Converts a given string into a list of words.
Use
re.findall()with the suppliedpatternto find all matching substrings.Omit the second argument to use the default regexp, which matches alphanumeric and hyphens.
Last updated
Was this helpful?