30 seconds of python

Snippet List

Click on a snippet’s name to view its code or a tag name to view all snippets in that category.

List

all_equal

Check if all elements in a list are equal.

Use [1:] and [:-1] to compare all the values in the given list.

all_unique

Returns True if all the values in a flat list are unique, False otherwise.

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

bifurcate

Splits values into two groups. If an element in filter is True, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.

Use list comprehension and enumerate() to add elements to groups, based on filter.

bifurcate_by

Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. If the function returns True, the element belongs to the first group; otherwise, it belongs to the second group.

Use list comprehension to add elements to groups, based on fn.

chunk

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 use created list.

compact

Removes falsey values from a list.

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

count_by

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

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.

count_occurences

Counts the occurrences of a value in a list.

Increment a counter for every item in the list that has the given value and is of the same type.

deep_flatten

Deep flattens a list.

Use recursion. Define a function, spread, that uses either list.extend() or list.append() on each element in a list to flatten it. Use list.extend() with an empty list and the spread function to flatten a list. Recursively flatten each element that is a list.

difference

Returns the difference between two iterables.

Create a set from b, then use list comprehension on a to only keep values not contained in the previously created set, _b.

difference_by

Returns the 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 b, then use list comprehension in combination with fn on a to only keep values not contained in the previously created set, _b.

every

Returns True if the provided function returns True for every element in the list, False otherwise.

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

every_nth

Returns every nth element in a list.

Use [nth-1::nth] to create a new list that contains every nth element of the given list.

filter_non_unique

Filters out the non-unique values in a list.

Use list comprehension and list.count() to create a list containing only the unique values.

flatten

Flattens a list of lists once.

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

group_by

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

Use map() and fn to map the values of the list to the keys of an object. Use list comprehension to map each element to the appropriate key.

has_duplicates

Returns True if there are duplicate values in a flast list, False otherwise.

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

head

Returns the head of a list.

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

initial

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

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

initialize_2d_list

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

Use list comprehension and range() to generate h rows where each is a list with length h, initialized with val. If val is not provided, default to None.

initialize_list_with_range

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.

initialize_list_with_values

Initializes and fills a list with the specified value.

Use 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.

intersection

Returns a list of elements that exist in both lists.

Create a set from b, then use list comprehension on a to only keep values contained in both lists.

intersection_by

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

Create a set by applying fn to each element in b, then use list comprehension in combination with fn on a to only keep values contained in both lists.

last

Returns the last element in a list.

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

longest_item

Takes any number of iterable objects or objects with a length property and returns the longest one. If multiple objects have the same length, the first one will be returned.

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

max_n

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

Use sorted() to sort the list, [:n] to get the specified number of elements. Omit the second argument, n, to get a one-element list.

min_n

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

Use sorted() to sort the list,[:n]to get the specified number of elements. Omit the second argument,n`, to get a one-element list.

none

Returns False if the provided function returns True for at least one element in the list, True otherwise.

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

offset

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

Use lst[offset:] and lst[:offset] to get the two slices of the list and combine them before returning.

sample

Returns a random element from an array.

Use randint() to generate a random number that corresponds to an index in the list, return the element at that index.

similarity

Returns a list of elements that exist in both lists.

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

some

Returns True if the provided function returns True for at least one element in the list, False otherwise.

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

spread

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.

symmetric_difference

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

Create a set from each list, then use list comprehension on each one to only keep values not contained in the previously created set of the other.

symmetric_difference_by

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, then use list comprehension in combination with fn on each one to only keep values not contained in the previously created set of the other.

tail

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

Return lst[1:] if the list's length is more than 1, otherwise, return the whole 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 convert to a list.

union_by

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, then use 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

unique_elements

Returns the unique elements in a given list.

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

zip

Creates a list of elements, grouped based on the position in the original lists.

Use max combined with list comprehension to get the length of the longest list in the arguments. Loop for max_length times grouping elements. If lengths of lists vary, use fill_value (defaults to None).

Math

average

Returns the average of two or more numbers.

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

average_by

Returns 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).

clamp_number

Clamps num within the inclusive range specified by the boundary values a and b.

If num falls within the range, return num. Otherwise, return the nearest number in the range.

digitize

Converts a number to an array of digits.

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

factorial

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.

fibonacci

Generates an array, containing the Fibonacci sequence, up until the nth term.

Starting with 0 and 1, use list.apoend() 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. Ifnis less or equal to0, return a list containing0`.

gcd

Calculates the greatest common divisor of a list of numbers.

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

in_range

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.

is_divisible

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.

is_even

Returns True if the given number is even, False otherwise.

Checks whether a number is odd or even using the modulo (%) operator. Returns True if the number is even, False if the number is odd.

is_odd

Returns True if the given number is odd, False otherwise.

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.

lcm

Returns the least common multiple of two or more numbers.

Define a function, spread, that uses either list.extend() or list.append() on each element in a list to flatten it. Use math.gcd() and lcm(x,y) = x * y / gcd(x,y) to determine the least common multiple.

max_by

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.

min_by

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.

rads_to_degrees

Converts an angle from radians to degrees.

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

sum_by

Returns 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.

String

byte_size

Returns the length of a string in bytes.

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

camel

Converts a string to camelcase.

Break the string into words and combine them capitalizing the first letter of each word, using a regexp, title() and lower.

capitalize

Capitalizes the first letter of a string.

Capitalize the first letter of the string and then add it with rest of the string. Omit the lower_rest parameter to keep the rest of the string intact, or set it to True to convert to lowercase.

capitalize_every_word

Capitalizes the first letter of every word in a string.

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

decapitalize

Decapitalizes the first letter of a string.

Decapitalize the first letter of the string and then add it with rest of the string. Omit the upper_rest parameter to keep the rest of the string intact, or set it to True to convert to uppercase.

is_anagram

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

Use str.replace() to remove spaces from both strings. Compare the lengths of the two strings, return False if they are not equal. Use sorted() on both strings and compare the results.

is_lower_case

Checks if a string is lower case.

Convert the given string to lower case, using str.lower() and compare it to the original.

is_upper_case

Checks if a string is upper case.

Convert the given string to upper case, using str.upper() and compare it to the original.

kebab

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

palindrome

Returns True if the given string is a palindrome, False otherwise.

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.

snake

Converts a string to snake case.

Break the string into words and combine them adding _-_ as a separator, using a regexp.

split_lines

Splits a multiline string into a list of lines.

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

Utility

cast_list

Casts the provided value as an array if it's not one.

Use isinstance() to check if the given value is a list and return it as-is or encapsulated in a list accordingly.

Object

keys_only

Returns 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.

map_values

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

Use dict.keys() to iterate over the object's keys, assigning the values produced by fn to each key of a new object.

values_only

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.


About

A few word about us, our goals and our projects.