- Equal list: Checks if all elements in a list are equal. Use
[1:]
and[:-1]
to compare all the values in the given list.
def all_equal(lst):
return lst[1:] == lst[:-1]
all_equal([1, 2, 3, 4, 5, 6]) # False
all_equal([1, 1, 1, 1]) # True
2. Unique items in list: Returns True
if all the values in a list are unique, False
otherwise. Use set()
on the given list to remove duplicates, use len()
to compare its length with the length of the list.
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]
all_unique(x) # True
all_unique(y) # False
3. Mean: Returns the average of two or more numbers. Use sum()
to sum all of the args
provided, divide by len(args)
.
def mean(*args):
return sum(args, 0.0) / len(args)
mean(*[1, 2, 3]) # 2.0
mean(1, 2, 3) # 2.0
Mean after mapping: 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)
.
def mean_by(lst, f=lambda el: el):
return sum(map(f, lst), 0.0) / len(lst)
mean_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda p: p['n']) # 5.0
4. Split list: 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
.
def split_list(lst, filter):
return [
[x for i, x in enumerate(lst) if filter[i] == True],
[x for i, x in enumerate(lst) if filter[i] == False]
]
split_list(
['beep', 'boop', 'foo', 'bar'],
[True, True, False, True]
) # [ ['beep', 'boop', 'bar'], ['foo'] ]
Split list by function: 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
.
def split_by(lst, fn):
return [
[x for x in lst if fn(x)],
[x for x in lst if not fn(x)]
]
split_by(
['beep', 'boop', 'foo', 'bar'],
lambda x: x[0] == 'b'
) # [ ['beep', 'boop', 'bar'], ['foo'] ]
5. String byte length: Returns the length of a string in bytes. Use s.encode('utf-8')
to encode the given string and return its length.
def byte_size(s):
return len(s.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11
6. Camelcase string: Converts a string to camelcase. Use re.sub()
to replace any -
or _
with a space, using the regexp r"(_|-)+"
. Use title()
to capitalize the first letter of each word convert the rest to lowercase. Finally, use replace()
to remove spaces between words.
from re import sub
def str_camelcase(s):
s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
return s[0].lower() + s[1:]
str_camelcase('some_database_field_name') # 'someDatabaseFieldName'
str_camelcase('Some label that needs to be camelized') # 'someLabelThatNeedsToBeCamelized'
str_camelcase('some-javascript-property') # 'someJavascriptProperty'
str_camelcase('some-mixed_string with spaces_underscores-and-hyphens') # 'someMixedStringWithSpacesUnderscoresAndHyphens'
7. Capitalize string: 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.
def str_capitalize(s, lower_rest=False):
return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])
str_capitalize('fooBar') # 'FooBar'
str_capitalize('fooBar', True) # 'Foobar'
Use s.title()
to capitalize first letter of every word in the string.
Decapitalize: 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.
def decapitalize(s, upper_rest=False):
return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'
8. Property of object: Given a predicate function, fn
, and a prop
string, this curried function will then take an object to inspect by calling the property and passing it to the predicate. Return a lambda
function that takes an object and applies the predicate function, fn
to the specified property.
def check_prop(fn, prop):
return lambda obj: fn(obj[prop])
check_age = check_prop(lambda x: x >= 18, 'age')
user = {'name': 'Mark', 'age': 18}
check_age(user) # True
9. Batch: 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.
from math import ceil
def batch(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
batch([1, 2, 3, 4, 5], 2) # [[1,2],[3,4],5]
10. Invert dictionary: Inverts a dictionary with non-unique hashable values. Use dictionary.items()
in combination with a loop to map the values of the dictionary to keys using dictionary.setdefault()
, list()
and append()
to create a list for each one.
def inverse_dict(obj):
inv_obj = {}
for key, value in obj.items():
inv_obj.setdefault(value, list()).append(key)
return inv_obj
ages = {
"Car": 5,
"Bat": 5,
"Ball": 8,
}
inverse_dict(ages) # { 5: ["Car", "Bat"], 8: ["Ball"] }
11. Drop false value: Removes false values from a list. Use filter()
to filter out false values (False
, None
, 0
, and ""
).
def dropna(lst):
return list(filter(None, lst))
dropna([0, 5, False, 3, '', None, 1, 'b', 'K', 78]) # [ 5, 3, 1, 'b', 'K', 78 ]
12. Deep flatten list: Use recursion. Use isinstance()
with collections.abc.Iterable
to check if an element is iterable. If it is, apply deep_flatten()
recursively, otherwise return [lst]
.
from collections.abc import Iterable
def deep_flatten(lst):
return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]