{ "data": [ { "id": "all_equal", "title": "all_equal", "type": "snippet", "attributes": { "fileName": "all_equal.md", "text": "Check if all elements in a list are equal.\n\nUse `[1:]` and `[:-1]` to compare all the values in the given list.\n\n", "codeBlocks": { "code": "def all_equal(lst):\n return lst[1:] == lst[:-1]", "example": "all_equal([1, 2, 3, 4, 5, 6]) # False\nall_equal([1, 1, 1, 1]) # True" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "6bf29cb176e4e9ce664ad04c6d262b6848f26639624dbb812eb1074d1c68b82a" } }, { "id": "all_unique", "title": "all_unique", "type": "snippet", "attributes": { "fileName": "all_unique.md", "text": "Returns `True` if all the values in a flat list are unique, `False` otherwise.\n\nUse `set()` on the given list to remove duplicates, compare its length with the length of the list.\n\n", "codeBlocks": { "code": "def all_unique(lst):\n return len(lst) == len(set(lst))", "example": "x = [1,2,3,4,5,6]\ny = [1,2,2,3,4,5]\nall_unique(x) # True\nall_unique(y) # False" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "ca101c9e623105dc857f1484fcea9211dda0dffc224834a5609d125257a7040f" } }, { "id": "average", "title": "average", "type": "snippet", "attributes": { "fileName": "average.md", "text": "Returns the average of two or more numbers.\n\nUse `sum()` to sum all of the `args` provided, divide by `len(args)`.\n\n", "codeBlocks": { "code": "def average(*args):\n return sum(args, 0.0) / len(args)", "example": "average(*[1, 2, 3]) # 2.0\naverage(1, 2, 3) # 2.0" }, "tags": [ "math", "list", "beginner" ] }, "meta": { "hash": "78bfdea5946774504eea1ba100974ad48ce8cb0a1ce1404cee8d885f35bb93a1" } }, { "id": "average_by", "title": "average_by", "type": "snippet", "attributes": { "fileName": "average_by.md", "text": "Returns the average of a list, after mapping each element to a value using the provided function.\n\nUse `map()` to map each element to the value returned by `fn`.\nUse `sum()` to sum all of the mapped values, divide by `len(lst)`.\n\n", "codeBlocks": { "code": "def average_by(lst, fn=lambda x: x):\n return sum(map(fn, lst), 0.0) / len(lst)", "example": "average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']) # 5.0" }, "tags": [ "math", "list", "function", "intermediate" ] }, "meta": { "hash": "8de876b55fd8b75ec395a5d70c29d83c7515d3ae2d59b9c7848e66e6cb854af0" } }, { "id": "bifurcate", "title": "bifurcate", "type": "snippet", "attributes": { "fileName": "bifurcate.md", "text": "Splits values into two groups. \nIf an element in `filter` is `True`, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.\n\nUse list comprehension and `enumerate()` to add elements to groups, based on `filter`.\n\n", "codeBlocks": { "code": "def bifurcate(lst, filter):\n return [\n [x for i,x in enumerate(lst) if filter[i] == True],\n [x for i,x in enumerate(lst) if filter[i] == False]\n ]", "example": "bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ]" }, "tags": [ "list", "intermediate" ] }, "meta": { "hash": "22c836b50fafc995904cc69096235ef9fb4c77a6faf38c4c5a4a88b2ed2126a8" } }, { "id": "bifurcate_by", "title": "bifurcate_by", "type": "snippet", "attributes": { "fileName": "bifurcate_by.md", "text": "Splits values into two groups according to a function, which specifies which group an element in the input list belongs to. \nIf the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group.\n\nUse list comprehension to add elements to groups, based on `fn`.\n\n", "codeBlocks": { "code": "def bifurcate_by(lst, fn):\n return [\n [x for x in lst if fn(x)],\n [x for x in lst if not fn(x)]\n ]", "example": "bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b') # [ ['beep', 'boop', 'bar'], ['foo'] ]" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "2e62d552ca03ff9bc39f920f4e24745945729ba35acc8ba75267b315a9b43563" } }, { "id": "byte_size", "title": "byte_size", "type": "snippet", "attributes": { "fileName": "byte_size.md", "text": "Returns the length of a string in bytes.\n\nUse `string.encode('utf-8')` to encode the given string and return its length.\n\n", "codeBlocks": { "code": "def byte_size(string):\n return len(string.encode('utf-8'))", "example": "byte_size('😀') # 4\nbyte_size('Hello World') # 11" }, "tags": [ "string", "beginner" ] }, "meta": { "hash": "ff655042992e2a6cded2c39439eca6a6542e4d7b4d019c9c8721fa61be6ccdb8" } }, { "id": "camel", "title": "camel", "type": "snippet", "attributes": { "fileName": "camel.md", "text": "Converts a string to camelcase.\n\nBreak the string into words and combine them capitalizing the first letter of each word, using a regexp, `title()` and `lower`.\n\n", "codeBlocks": { "code": "import re\n\ndef camel(s):\n s = re.sub(r\"(\\s|_|-)+\", \" \", s).title().replace(\" \", \"\")\n return s[0].lower() + s[1:]", "example": "camel('some_database_field_name'); # 'someDatabaseFieldName'\ncamel('Some label that needs to be camelized'); # 'someLabelThatNeedsToBeCamelized'\ncamel('some-javascript-property'); # 'someJavascriptProperty'\ncamel('some-mixed_string with spaces_underscores-and-hyphens'); # 'someMixedStringWithSpacesUnderscoresAndHyphens'" }, "tags": [ "string", "regexp", "intermediate" ] }, "meta": { "hash": "60b308cb7f28b676fb122949d04ae07af0d4e0fcb96f037b3aa3c09be9b2e7ab" } }, { "id": "capitalize", "title": "capitalize", "type": "snippet", "attributes": { "fileName": "capitalize.md", "text": "Capitalizes the first letter of a string.\n\nCapitalize the first letter of the string and then add it with rest of the string. \nOmit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase.\n\n", "codeBlocks": { "code": "def capitalize(string, lower_rest=False):\n return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])", "example": "capitalize('fooBar') # 'FooBar'\ncapitalize('fooBar', True) # 'Foobar'" }, "tags": [ "string", "intermediate" ] }, "meta": { "hash": "f4b0ecfe5d6eb18a65699fbe706737723c2c0de6a16e07e4c7686e9ecbad29c5" } }, { "id": "capitalize_every_word", "title": "capitalize_every_word", "type": "snippet", "attributes": { "fileName": "capitalize_every_word.md", "text": "Capitalizes the first letter of every word in a string.\n\nUse `string.title()` to capitalize first letter of every word in the string.\n\n", "codeBlocks": { "code": "def capitalize_every_word(string):\n return string.title()", "example": "capitalize_every_word('hello world!') # 'Hello World!'" }, "tags": [ "string", "beginner" ] }, "meta": { "hash": "ec399b1f2bcb0888956d1ecb40fd509f22ba902cd7f3c53af02729d52f021f86" } }, { "id": "cast_list", "title": "cast_list", "type": "snippet", "attributes": { "fileName": "cast_list.md", "text": "Casts the provided value as an array if it's not one.\n\nUse `isinstance()` to check if the given value is a list and return it as-is or encapsulated in a list accordingly.\n\n", "codeBlocks": { "code": "def cast_list(val):\n return val if isinstance(val, list) else [val]", "example": "cast_list('foo'); # ['foo']\ncast_list([1]); # [1]" }, "tags": [ "utility", "list", "beginner" ] }, "meta": { "hash": "4a9cb79c384099543163d3b1b7e2fa389a4cc373b2b76b17563a4597ed29a4c7" } }, { "id": "chunk", "title": "chunk", "type": "snippet", "attributes": { "fileName": "chunk.md", "text": "Chunks a list into smaller lists of a specified size.\n\nUse `list()` and `range()` to create a list of the desired `size`.\nUse `map()` on the list and fill it with splices of the given list.\nFinally, return use created list.\n\n", "codeBlocks": { "code": "from math import ceil\n\ndef chunk(lst, size):\n return list(\n map(lambda x: lst[x * size:x * size + size],\n list(range(0, ceil(len(lst) / size)))))", "example": "chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]" }, "tags": [ "list", "intermediate" ] }, "meta": { "hash": "f8c9cdb2261bfe2932bc7d3d11853a3d42d468a88ad515e9f15d9abffe9b30a6" } }, { "id": "clamp_number", "title": "clamp_number", "type": "snippet", "attributes": { "fileName": "clamp_number.md", "text": "Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.\n\nIf `num` falls within the range, return `num`. \nOtherwise, return the nearest number in the range.\n\n", "codeBlocks": { "code": "def clamp_number(num,a,b):\n return max(min(num, max(a,b)),min(a,b))", "example": "clamp_number(2, 3, 5) # 3\nclamp_number(1, -1, -5) # -1" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "7e3dc4519a629ec87f72e5b495227733735c9c2262e5f6a89264191967cfad31" } }, { "id": "compact", "title": "compact", "type": "snippet", "attributes": { "fileName": "compact.md", "text": "Removes falsey values from a list.\n\nUse `filter()` to filter out falsey values (`False`, `None`, `0`, and `\"\"`).\n\n", "codeBlocks": { "code": "def compact(lst):\n return list(filter(bool, lst))", "example": "compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "6b98c58b6aecf1b58ed36f55a407bf2f2d68938723d37472fe43d9e652d93fe6" } }, { "id": "count_by", "title": "count_by", "type": "snippet", "attributes": { "fileName": "count_by.md", "text": "Groups the elements of a list based on the given function and returns the count of elements in each group.\n\nUse `map()` to map the values of the given list using the given function.\nIterate over the map and increase the element count each time it occurs.\n\n", "codeBlocks": { "code": "def count_by(arr, fn=lambda x: x):\n key = {}\n for el in map(fn, arr):\n key[el] = 1 if el not in key else key[el] + 1\n return key", "example": "from math import floor\ncount_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}\ncount_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}" }, "tags": [ "list", "intermediate" ] }, "meta": { "hash": "bcbf6bf4eea87d50914f20640482d6e25198357ac3ec5155276664905ac1e5e0" } }, { "id": "count_occurences", "title": "count_occurences", "type": "snippet", "attributes": { "fileName": "count_occurences.md", "text": "Counts the occurrences of a value in a list.\n\nIncrement a counter for every item in the list that has the given value and is of the same type.\n\n", "codeBlocks": { "code": "def count_occurrences(lst, val):\n return len([x for x in lst if x == val and type(x) == type(val)])", "example": "count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "eee88217431699369070beb38ca0265d963c78321bfd98de9e3a38533c6ee90e" } }, { "id": "decapitalize", "title": "decapitalize", "type": "snippet", "attributes": { "fileName": "decapitalize.md", "text": "Decapitalizes the first letter of a string.\n\nDecapitalize the first letter of the string and then add it with rest of the string. \nOmit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase.\n\n", "codeBlocks": { "code": "def decapitalize(string, upper_rest=False):\n return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])", "example": "decapitalize('FooBar') # 'fooBar'\ndecapitalize('FooBar', True) # 'fOOBAR'" }, "tags": [ "string", "intermediate" ] }, "meta": { "hash": "aea9a271d47a5606912e2482b8cc6bfb7b7382c4d0c86545b194cc0ad5f342b5" } }, { "id": "deep_flatten", "title": "deep_flatten", "type": "snippet", "attributes": { "fileName": "deep_flatten.md", "text": "Deep flattens a list.\n\nUse recursion. \nDefine a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.\nUse `list.extend()` with an empty list and the `spread` function to flatten a list.\nRecursively flatten each element that is a list.\n\n", "codeBlocks": { "code": "def spread(arg):\n ret = []\n for i in arg:\n if isinstance(i, list):\n ret.extend(i)\n else:\n ret.append(i)\n return ret\n\ndef deep_flatten(lst):\n result = []\n result.extend(\n spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))\n return result", "example": "deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]" }, "tags": [ "list", "recursion", "intermediate" ] }, "meta": { "hash": "a100d5704afe48a7dce26871bc50c993670d7388d8e4958c02c07efe07884167" } }, { "id": "difference", "title": "difference", "type": "snippet", "attributes": { "fileName": "difference.md", "text": "Returns the difference between two iterables.\n\nCreate a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`.\n\n", "codeBlocks": { "code": "def difference(a, b):\n _b = set(b)\n return [item for item in a if item not in _b]", "example": "difference([1, 2, 3], [1, 2, 4]) # [3]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "479fcdba73e7429ccb82649a354159ad9008c63f852c960d6733c10ecafceae3" } }, { "id": "difference_by", "title": "difference_by", "type": "snippet", "attributes": { "fileName": "difference_by.md", "text": "Returns the difference between two lists, after applying the provided function to each list element of both.\n\nCreate 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`.\n\n", "codeBlocks": { "code": "def difference_by(a, b, fn):\n _b = set(map(fn, b))\n return [item for item in a if fn(item) not in _b]", "example": "from math import floor\ndifference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]\ndifference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "a240b4f3152f847cb5f3877ab2fa1f4b75259c5ce11e28a773ad34bdba14f0a8" } }, { "id": "digitize", "title": "digitize", "type": "snippet", "attributes": { "fileName": "digitize.md", "text": "Converts a number to an array of digits.\n\nUse `map()` combined with `int` on the string representation of `n` and return a list from the result.\n\n", "codeBlocks": { "code": "def digitize(n):\n return list(map(int, str(n)))", "example": "digitize(123) # [1, 2, 3]" }, "tags": [ "math", "list", "beginner" ] }, "meta": { "hash": "576de2896d2565d44da5d42b4b57b37cf1b2e5fc69103ab48a9ed532040ffaf2" } }, { "id": "every", "title": "every", "type": "snippet", "attributes": { "fileName": "every.md", "text": "Returns `True` if the provided function returns `True` for every element in the list, `False` otherwise.\n\nUse `all()` in combination with `map` and `fn` to check if `fn` returns `True` for all elements in the list.\n\n", "codeBlocks": { "code": "def every(lst, fn=lambda x: x):\n return all(map(fn, lst))", "example": "every([4, 2, 3], lambda x: x > 1) # True\nevery([1, 2, 3]) # True" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "40b8ce30ab95e515b6814e602a7f0755124b792d6f9c664f58e0ee61c27148c1" } }, { "id": "every_nth", "title": "every_nth", "type": "snippet", "attributes": { "fileName": "every_nth.md", "text": "Returns every nth element in a list.\n\nUse `[nth-1::nth]` to create a new list that contains every nth element of the given list.\n\n", "codeBlocks": { "code": "def every_nth(lst, nth):\n return lst[nth-1::nth]", "example": "every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "038e0fd0752bbd88c73ea9059e10768bbf31fd3178113738064405e010aa8aa7" } }, { "id": "factorial", "title": "factorial", "type": "snippet", "attributes": { "fileName": "factorial.md", "text": "Calculates the factorial of a number.\n\nUse recursion. \nIf `num` is less than or equal to `1`, return `1`. \nOtherwise, return the product of `num` and the factorial of `num - 1`. \nThrows an exception if `num` is a negative or a floating point number.\n\n", "codeBlocks": { "code": "def factorial(num):\n if not ((num >= 0) and (num % 1 == 0)):\n raise Exception(\n f\"Number( {num} ) can't be floating point or negative \")\n return 1 if num == 0 else num * factorial(num - 1)", "example": "factorial(6) # 720" }, "tags": [ "math", "recursion", "beginner" ] }, "meta": { "hash": "948d8f496825413a0047464055ab9166016ad526d26d83f3ceacd3dc5a1926ba" } }, { "id": "fibonacci", "title": "fibonacci", "type": "snippet", "attributes": { "fileName": "fibonacci.md", "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nStarting 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 reaches `n`. \nIf `n` is less or equal to `0`, return a list containing `0`.\n\n", "codeBlocks": { "code": "def fibonacci(n):\r\n if n <= 0:\r\n return [0]\r\n\r\n sequence = [0, 1]\r\n while len(sequence) <= n:\r\n next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]\r\n sequence.append(next_value)\r\n\r\n return sequence", "example": "fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]" }, "tags": [ "math", "list", "intermediate" ] }, "meta": { "hash": "cf0354a54a2bdd1d2423ff767f1d568f65c41a3db8863ab027a7536468d602f7" } }, { "id": "filter_non_unique", "title": "filter_non_unique", "type": "snippet", "attributes": { "fileName": "filter_non_unique.md", "text": "Filters out the non-unique values in a list.\n\nUse list comprehension and `list.count()` to create a list containing only the unique values.\n\n", "codeBlocks": { "code": "def filter_non_unique(lst):\n return [item for item in lst if lst.count(item) == 1]", "example": "filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "05679ae115d276830ec769a04b0800d92eabc6a09678fc1a9cf6013c813cc650" } }, { "id": "flatten", "title": "flatten", "type": "snippet", "attributes": { "fileName": "flatten.md", "text": "Flattens a list of lists once.\n\nUse nested list comprehension to extract each value from sub-lists in order.\n\n", "codeBlocks": { "code": "def flatten(lst):\n return [x for y in lst for x in y]", "example": "flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]" }, "tags": [ "list", "intermediate" ] }, "meta": { "hash": "49b4f976c9050c9cb6fe038653fc3dbc88135086255c06c4f46b746b21bfb544" } }, { "id": "gcd", "title": "gcd", "type": "snippet", "attributes": { "fileName": "gcd.md", "text": "Calculates the greatest common divisor of a list of numbers.\n\nUse `reduce()` and `math.gcd` over the given list.\n\n", "codeBlocks": { "code": "from functools import reduce\nimport math\n\ndef gcd(numbers):\n return reduce(math.gcd, numbers)", "example": "gcd([8,36,28]) # 4" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "dbb01e7253dbb6f3e2f53271fc14fb7b3ee9816fe56266f78a54b4ca21c94cd7" } }, { "id": "group_by", "title": "group_by", "type": "snippet", "attributes": { "fileName": "group_by.md", "text": "Groups the elements of a list based on the given function.\n\nUse `map()` and `fn` to map the values of the list to the keys of an object.\nUse list comprehension to map each element to the appropriate `key`.\n\n", "codeBlocks": { "code": "def group_by(lst, fn):\n return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}", "example": "import math\ngroup_by([6.1, 4.2, 6.3], math.floor) # {4: [4.2], 6: [6.1, 6.3]}\ngroup_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}" }, "tags": [ "list", "object", "beginner" ] }, "meta": { "hash": "51e158e03a090b891d6d1646644bff5163751b25a7ee3e72280c04570bff2429" } }, { "id": "has_duplicates", "title": "has_duplicates", "type": "snippet", "attributes": { "fileName": "has_duplicates.md", "text": "Returns `True` if there are duplicate values in a flast list, `False` otherwise.\n\nUse `set()` on the given list to remove duplicates, compare its length with the length of the list.\n\n", "codeBlocks": { "code": "def has_duplicates(lst):\n return len(lst) != len(set(lst))", "example": "x = [1,2,3,4,5,5]\ny = [1,2,3,4,5]\nhas_duplicates(x) # True\nhas_duplicates(y) # False" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "762663e25e978ee96720d6fd977e4ca42b328150fa654d0e600c636284552712" } }, { "id": "head", "title": "head", "type": "snippet", "attributes": { "fileName": "head.md", "text": "Returns the head of a list.\n\nuse `lst[0]` to return the first element of the passed list.\n\n", "codeBlocks": { "code": "def head(lst):\n return lst[0]", "example": "head([1, 2, 3]); # 1" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "6c86b52c2c7a56a4527114736664a3720b2026d2419b87daf36de6877ad0e4b0" } }, { "id": "in_range", "title": "in_range", "type": "snippet", "attributes": { "fileName": "in_range.md", "text": "Checks if the given number falls within the given range.\n\nUse arithmetic comparison to check if the given number is in the specified range.\nIf the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.\n\n", "codeBlocks": { "code": "def in_range(n, start, end = 0):\n if (start > end):\n end, start = start, end\n return start <= n <= end", "example": "in_range(3, 2, 5); # True\nin_range(3, 4); # True\nin_range(2, 3, 5); # False\nin_range(3, 2); # False" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "f65d098189837551aef365c68bd9389a0c1e84e89233fa5a886e889ce6981f9f" } }, { "id": "initial", "title": "initial", "type": "snippet", "attributes": { "fileName": "initial.md", "text": "Returns all the elements of a list except the last one.\n\nUse `lst[0:-1]` to return all but the last element of the list.\n\n", "codeBlocks": { "code": "def initial(lst):\n return lst[0:-1]", "example": "initial([1, 2, 3]); # [1,2]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "cf0229dd484711e5847d85952841a13800bb5e0767c1de40e219f63cfed3e0f1" } }, { "id": "initialiaze_2d_list", "title": "initialize_2d_list", "type": "snippet", "attributes": { "fileName": "initialiaze_2d_list.md", "text": "Initializes a 2D list of given width and height and value.\n\nUse list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`.\nIf `val` is not provided, default to `None`.\n\n", "codeBlocks": { "code": "def initialize_2d_list(w,h, val = None):\n return [[val for x in range(w)] for y in range(h)]", "example": "initialize_2d_list(2, 2, 0) # [[0,0], [0,0]]" }, "tags": [ "list", "intermediate" ] }, "meta": { "hash": "0dea8eb7639aa7d0b2748ecfaeb80b1a93408340b6f697f604451b8e9442f477" } }, { "id": "initialize_list_with_range", "title": "initialize_list_with_range", "type": "snippet", "attributes": { "fileName": "initialize_list_with_range.md", "text": "Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.\n\nUse `list` and `range()` to generate a list of the appropriate length, filled with the desired values in the given range.\nOmit `start` to use the default value of `0`.\nOmit `step` to use the default value of `1`.\n\n", "codeBlocks": { "code": "def initialize_list_with_range(end, start = 0, step = 1):\n return list(range(start, end + 1, step))", "example": "initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]\ninitialize_list_with_range(7,3) # [3, 4, 5, 6, 7]\ninitialize_list_with_range(9,0,2) # [0, 2, 4, 6, 8]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "75ce66f70653b918d86f8bb7c2743bced720389c9f8f97072b4ff90b377255e1" } }, { "id": "initialize_list_with_values", "title": "initialize_list_with_values", "type": "snippet", "attributes": { "fileName": "initialize_list_with_values.md", "text": "Initializes and fills a list with the specified value.\n\nUse list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values.\nOmit `val` to use the default value of `0`.\n\n", "codeBlocks": { "code": "def initialize_list_with_values(n, val = 0):\n return [val for x in range(n)]", "example": "initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "87604b968fccbc3d60399619b388f5939d646059db467fc2c86f99138f68b952" } }, { "id": "intersection", "title": "intersection", "type": "snippet", "attributes": { "fileName": "intersection.md", "text": "Returns a list of elements that exist in both lists.\n\nCreate a `set` from `b`, then use list comprehension on `a` to only keep values contained in both lists.\n\n", "codeBlocks": { "code": "def intersection(a, b):\n _b = set(b)\n return [item for item in a if item in _b]", "example": "intersection([1, 2, 3], [4, 3, 2]) # [2, 3]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "a332cce7b7d7e303469e8c39c4926bf92ecb12847c3932985cc633e3a85a23bb" } }, { "id": "intersection_by", "title": "intersection_by", "type": "snippet", "attributes": { "fileName": "intersection_by.md", "text": "Returns a list of elements that exist in both lists, after applying the provided function to each list element of both.\n\nCreate 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.\n\n", "codeBlocks": { "code": "def intersection_by(a, b, fn):\n _b = set(map(fn, b))\n return [item for item in a if fn(item) in _b]", "example": "from math import floor\nintersection_by([2.1, 1.2], [2.3, 3.4],floor) # [2.1]" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "eb4bff1a92a7848c8184531fee590e8f060a6d4f6ffe214aec4ccda7a5e18031" } }, { "id": "is_anagram", "title": "is_anagram", "type": "snippet", "attributes": { "fileName": "is_anagram.md", "text": "Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).\n\nUse `str.replace()` to remove spaces from both strings.\nCompare the lengths of the two strings, return `False` if they are not equal.\nUse `sorted()` on both strings and compare the results.\n\n", "codeBlocks": { "code": "def is_anagram(str1, str2):\n _str1, _str2 = str1.replace(\" \", \"\"), str2.replace(\" \", \"\")\n\n if len(_str1) != len(_str2):\n return False\n else:\n return sorted(_str1.lower()) == sorted(_str2.lower())", "example": "is_anagram(\"anagram\", \"Nag a ram\") # True" }, "tags": [ "string", "intermediate" ] }, "meta": { "hash": "3080e22832c2a393f1546f4cff18b15b701fbe27dc2368fd26700a05f2f109a2" } }, { "id": "is_divisible", "title": "is_divisible", "type": "snippet", "attributes": { "fileName": "is_divisible.md", "text": "Checks if the first numeric argument is divisible by the second one.\n\nUse the modulo operator (`%`) to check if the remainder is equal to `0`.\n\n", "codeBlocks": { "code": "def is_divisible(dividend, divisor):\n return dividend % divisor == 0", "example": "is_divisible(6, 3) # True" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "e6272becc36195e4b76f62baa61d43d9de5472201d1fb589e18bd5f47d6d57b0" } }, { "id": "is_even", "title": "is_even", "type": "snippet", "attributes": { "fileName": "is_even.md", "text": "Returns `True` if the given number is even, `False` otherwise.\n\nChecks whether a number is odd or even using the modulo (`%`) operator. \nReturns `True` if the number is even, `False` if the number is odd.\n\n", "codeBlocks": { "code": "def is_even(num):\n return num % 2 == 0", "example": "is_even(3) # False" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "354d3fcfa67b5df106c0ff528246bfacd2d7cec4942a7c3a904d87e76d7dae11" } }, { "id": "is_odd", "title": "is_odd", "type": "snippet", "attributes": { "fileName": "is_odd.md", "text": "Returns `True` if the given number is odd, `False` otherwise.\n\nChecks whether a number is even or odd using the modulo (`%`) operator. \nReturns `True` if the number is odd, `False` if the number is even.\n\n", "codeBlocks": { "code": "def is_odd(num):\n return num % 2 != 0", "example": "is_odd(3) # True" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "261771aa5fd9c9dcb60dd93c29afce0de3a51c505e474fa7c76789a1e0d8f5c8" } }, { "id": "kebab", "title": "kebab", "type": "snippet", "attributes": { "fileName": "kebab.md", "text": "Converts a string to kebab case.\n\nBreak the string into words and combine them adding `-` as a separator, using a regexp.\n\n", "codeBlocks": { "code": "import re\n\ndef kebab(str):\n return re.sub(r\"(\\s|_|-)+\",\"-\",\n re.sub(r\"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+\",\n lambda mo: mo.group(0).lower(),str)\n )", "example": "kebab('camelCase'); # 'camel-case'\nkebab('some text'); # 'some-text'\nkebab('some-mixed_string With spaces_underscores-and-hyphens'); # 'some-mixed-string-with-spaces-underscores-and-hyphens'\nkebab('AllThe-small Things'); # \"all-the-small-things\"" }, "tags": [ "string", "regexp", "intermediate" ] }, "meta": { "hash": "374b7c60d87e6fa52b1bb0176f9c762d8061262d0843cf82ad3ab1d4744ab22e" } }, { "id": "keys_only", "title": "keys_only", "type": "snippet", "attributes": { "fileName": "keys_only.md", "text": "Returns a flat list of all the keys in a flat dictionary.\n\nUse `dict.keys()` to return the keys in the given dictionary.\nReturn a `list()` of the previous result.\n\n", "codeBlocks": { "code": "def keys_only(flat_dict):\n return list(flat_dict.keys())", "example": "ages = {\n \"Peter\": 10,\n \"Isabel\": 11,\n \"Anna\": 9,\n}\nkeys_only(ages) # ['Peter', 'Isabel', 'Anna']" }, "tags": [ "object", "list", "beginner" ] }, "meta": { "hash": "4e4a5b4892fcccb2982e7ae352f9d61fa0234c209431c9461ea47d503feaaf49" } }, { "id": "last", "title": "last", "type": "snippet", "attributes": { "fileName": "last.md", "text": "Returns the last element in a list.\n\nuse `lst[-1]` to return the last element of the passed list.\n\n", "codeBlocks": { "code": "def last(lst):\n return lst[-1]", "example": "last([1, 2, 3]) # 3" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "7fc339fbdb18e993fc93950b307fe2ec792c3f010f5dee0971d02288af16d67b" } }, { "id": "lcm", "title": "lcm", "type": "snippet", "attributes": { "fileName": "lcm.md", "text": "Returns the least common multiple of two or more numbers.\n\nDefine a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.\nUse `math.gcd()` and `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple.\n\n", "codeBlocks": { "code": "from functools import reduce\nimport math\n\ndef spread(arg):\n ret = []\n for i in arg:\n if isinstance(i, list):\n ret.extend(i)\n else:\n ret.append(i)\n return ret\n\ndef lcm(*args):\n numbers = []\n numbers.extend(spread(list(args)))\n\n def _lcm(x, y):\n return int(x * y / math.gcd(x, y))\n\n return reduce((lambda x, y: _lcm(x, y)), numbers)", "example": "lcm(12, 7) # 84\nlcm([1, 3, 4], 5) # 60" }, "tags": [ "math", "list", "recursion", "advanced" ] }, "meta": { "hash": "a0cf166fd37f16c6bcaef46345ff11af0dadb488160168a0915e665550f7a669" } }, { "id": "longest_item", "title": "longest_item", "type": "snippet", "attributes": { "fileName": "longest_item.md", "text": "Takes any number of iterable objects or objects with a length property and returns the longest one. \nIf multiple objects have the same length, the first one will be returned.\n\nUse `max()` with `len` as the `key` to return the item with the greatest length.\n\n", "codeBlocks": { "code": "def longest_item(*args):\n return max(args, key = len)", "example": "longest_item('this', 'is', 'a', 'testcase') # 'testcase'\nlongest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5]\nlongest_item([1, 2, 3], 'foobar') # 'foobar'" }, "tags": [ "list", "string", "utility", "intermediate" ] }, "meta": { "hash": "dd1a2d1300f23bb8f8618f9ab20dad11062f4476be80081e3cefc535717da818" } }, { "id": "map_values", "title": "map_values", "type": "snippet", "attributes": { "fileName": "map_values.md", "text": "Creates an object with the same keys as the provided object and values generated by running the provided function for each value.\n\nUse `dict.keys()` to iterate over the object's keys, assigning the values produced by `fn` to each key of a new object.\n\n", "codeBlocks": { "code": "def map_values(obj, fn):\n ret = {}\n for key in obj.keys():\n ret[key] = fn(obj[key])\n return ret", "example": "users = {\n 'fred': { 'user': 'fred', 'age': 40 },\n 'pebbles': { 'user': 'pebbles', 'age': 1 }\n}\n\nmap_values(users, lambda u : u['age']) # {'fred': 40, 'pebbles': 1}" }, "tags": [ "object", "function", "intermediate" ] }, "meta": { "hash": "91f93e124e2f1fb9d25b62db478f91503330947a7c212dc97215dec8c4b225fe" } }, { "id": "max_by", "title": "max_by", "type": "snippet", "attributes": { "fileName": "max_by.md", "text": "Returns the maximum value of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `max()` to return the maximum value.\n\n", "codeBlocks": { "code": "def max_by(lst, fn):\n return max(map(fn,lst))", "example": "max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 8" }, "tags": [ "math", "list", "function", "beginner" ] }, "meta": { "hash": "aca578491d9c055c793cf782db88f7e0c1de093c3e9ad09a72a59e75055b7581" } }, { "id": "max_n", "title": "max_n", "type": "snippet", "attributes": { "fileName": "max_n.md", "text": "Returns the `n` maximum elements from the provided list. \nIf `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order).\n\nUse `sorted()` to sort the list, `[:n]` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element list.\n\n", "codeBlocks": { "code": "def max_n(lst, n=1):\n return sorted(lst, reverse=True)[:n]", "example": "max_n([1, 2, 3]) # [3]\nmax_n([1, 2, 3], 2) # [3,2]" }, "tags": [ "list", "math", "beginner" ] }, "meta": { "hash": "a87775ce6bd1590c7c7b31b7dfce03b00120e4e8183c65cec8fdd3841fa369d7" } }, { "id": "min_by", "title": "min_by", "type": "snippet", "attributes": { "fileName": "min_by.md", "text": "Returns the minimum value of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `min()` to return the minimum value.\n\n", "codeBlocks": { "code": "def min_by(lst, fn):\n return min(map(fn,lst))", "example": "min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 2" }, "tags": [ "math", "list", "function", "beginner" ] }, "meta": { "hash": "fb061014007b8c476b42e8c7f8619a6a203f89e6141960a80292dc362ad05f80" } }, { "id": "min_n", "title": "min_n", "type": "snippet", "attributes": { "fileName": "min_n.md", "text": "Returns the `n` minimum elements from the provided list. \nIf `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).\n\nUse `sorted() to sort the list, `[:n]` to get the specified number of elements.\nOmit the second argument, `n`, to get a one-element list.\n\n", "codeBlocks": { "code": "def min_n(lst, n=1):\n return sorted(lst, reverse=False)[:n]", "example": "min_n([1, 2, 3]) # [1]\nmin_n([1, 2, 3], 2) # [1,2]" }, "tags": [ "list", "math", "beginner" ] }, "meta": { "hash": "c920b58f01c63346e65eab83a60c4635d4c104e41767b9d41ad94029e662b902" } }, { "id": "n_times_string", "title": "n_times_string", "type": "snippet", "attributes": { "fileName": "n_times_string.md", "text": "Prints out the same string a defined number of times.\n\nRepeat the string `n` times, using the `*` operator.\n\n", "codeBlocks": { "code": "def n_times_string(str,n):\r\n return (str * n)", "example": "n_times_string('py', 4) #'pypypypy'" }, "tags": [ "string", "beginner" ] }, "meta": { "hash": "5f815cfc58d3339f19b865433b2965a08e64f336e1747009e915883096deb26b" } }, { "id": "none", "title": "none", "type": "snippet", "attributes": { "fileName": "none.md", "text": "Returns `False` if the provided function returns `True` for at least one element in the list, `True` otherwise.\n\nUse `all()` and `fn` to check if `fn` returns `False` for all the elements in the list.\n\n", "codeBlocks": { "code": "def none(lst, fn=lambda x: x):\n return all(not fn(x) for x in lst)", "example": "none([0, 1, 2, 0], lambda x: x >= 2 ) # False\nnone([0, 0, 0]) # True" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "0dd3614b71e7a0b646a084e991eb6b4b2940492a14e6b8159d5d8a60a5abe04d" } }, { "id": "offset", "title": "offset", "type": "snippet", "attributes": { "fileName": "offset.md", "text": "Moves the specified amount of elements to the end of the list.\n\nUse `lst[offset:]` and `lst[:offset]` to get the two slices of the list and combine them before returning.\n\n", "codeBlocks": { "code": "def offset(lst, offset):\n return lst[offset:] + lst[:offset]", "example": "offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]\noffset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "1be5e82e22a183c88351baa1cc14cab498e20dd17d6096de7915f6dcb16c76b9" } }, { "id": "palindrome", "title": "palindrome", "type": "snippet", "attributes": { "fileName": "palindrome.md", "text": "Returns `True` if the given string is a palindrome, `False` otherwise.\n\nUse `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string. \nThen, compare the new string with its reverse.\n\n", "codeBlocks": { "code": "from re import sub\n\ndef palindrome(string):\n s = sub('[\\W_]', '', string.lower())\n return s == s[::-1]", "example": "palindrome('taco cat') # True" }, "tags": [ "string", "intermediate" ] }, "meta": { "hash": "e707d6b2f27bcc3dda322b114199b2b22ea916871b1c657c43648ecb5b21240b" } }, { "id": "rads_to_degrees", "title": "rads_to_degrees", "type": "snippet", "attributes": { "fileName": "rads_to_degrees.md", "text": "Converts an angle from radians to degrees.\n\nUse `math.pi` and the radian to degree formula to convert the angle from radians to degrees.\n\n", "codeBlocks": { "code": "import math\n\ndef rads_to_degrees(rad):\n return (rad * 180.0) / math.pi", "example": "import math\nrads_to_degrees(math.pi / 2) # 90.0" }, "tags": [ "math", "beginner" ] }, "meta": { "hash": "c3008a44f2eb31adaca3e4f91c29a56a955e3105f9c187aa055fc55c35874b41" } }, { "id": "sample", "title": "sample", "type": "snippet", "attributes": { "fileName": "sample.md", "text": "Returns a random element from an array.\n\nUse `randint()` to generate a random number that corresponds to an index in the list, return the element at that index.\n\n", "codeBlocks": { "code": "from random import randint\n\ndef sample(lst):\n return lst[randint(0, len(lst) - 1)]", "example": "sample([3, 7, 9, 11]) # 9" }, "tags": [ "list", "random", "beginner" ] }, "meta": { "hash": "68c3a2f20c4969324199dc6005be573d95ec4d08747586bf26d0bf06b571c94c" } }, { "id": "shuffle", "title": "shuffle", "type": "snippet", "attributes": { "fileName": "shuffle.md", "text": "Randomizes the order of the values of an list, returning a new list.\n\nUses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.\n\n", "codeBlocks": { "code": "from copy import deepcopy\nfrom random import randint\n\ndef shuffle(lst):\n temp_lst = deepcopy(lst)\n m = len(temp_lst)\n while (m):\n m -= 1\n i = randint(0, m)\n temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]\n return temp_lst", "example": "foo = [1,2,3]\nshuffle(foo) # [2,3,1] , foo = [1,2,3]" }, "tags": [ "list", "random", "intermediate" ] }, "meta": { "hash": "8c6e1dafadd78f04b11d412b7b8db01e1275339adf906e2637129d761117e480" } }, { "id": "similarity", "title": "similarity", "type": "snippet", "attributes": { "fileName": "similarity.md", "text": "Returns a list of elements that exist in both lists.\n\nUse list comprehension on `a` to only keep values contained in both lists.\n\n", "codeBlocks": { "code": "def similarity(a, b):\n return [item for item in a if item in b]", "example": "similarity([1, 2, 3], [1, 2, 4]) # [1, 2]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "51e5a4fc0b3376f24804b51f71c3daed109b1e60535aa39bca44c1918fedaacf" } }, { "id": "snake", "title": "snake", "type": "snippet", "attributes": { "fileName": "snake.md", "text": "Converts a string to snake case.\n\nBreak the string into words and combine them adding `_-_` as a separator, using a regexp.\n\n", "codeBlocks": { "code": "import re\n\ndef snake(str):\n return re.sub(r\"(\\s|_|-)+\",\"_\",\n re.sub(r\"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+\",\n lambda mo: mo.group(0).lower(),str)\n )", "example": "snake('camelCase') # 'camel_case'\nsnake('some text') # 'some_text'\nsnake('some-mixed_string With spaces_underscores-and-hyphens') # 'some_mixed_string_with_spaces_underscores_and_hyphens'\nsnake('AllThe-small Things') # \"all_the_smal_things\"" }, "tags": [ "string", "regexp", "intermediate" ] }, "meta": { "hash": "4217b274beb495919f1aa33afe8e910d04776c35685f01ba4b3fcdd0b176e6e1" } }, { "id": "some", "title": "some", "type": "snippet", "attributes": { "fileName": "some.md", "text": "Returns `True` if the provided function returns `True` for at least one element in the list, `False` otherwise.\n\nUse `any()` in combination with `map()` and `fn` to check if `fn` returns `True` for any element in the list.\n\n", "codeBlocks": { "code": "def some(lst, fn=lambda x: x):\n return any(map(fn, lst))", "example": "some([0, 1, 2, 0], lambda x: x >= 2 ) # True\nsome([0, 0, 1, 0]) # True" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "b104995e92213cbfeac2dce438e9d6f8fd13e18b8fb106789efa06f9285da2bb" } }, { "id": "split_lines", "title": "split_lines", "type": "snippet", "attributes": { "fileName": "split_lines.md", "text": "Splits a multiline string into a list of lines.\n\nUse `str.split()` and `'\\n'` to match line breaks and create a list.\n\n", "codeBlocks": { "code": "def split_lines(str):\n return str.split('\\n')", "example": "split_lines('This\\nis a\\nmultiline\\nstring.\\n') # 'This\\nis a\\nmultiline\\nstring.\\n'" }, "tags": [ "string", "beginner" ] }, "meta": { "hash": "db5b597fccad7226629e99e4f41eaa56a7783dd611952b3e2b6711fb85b12c25" } }, { "id": "spread", "title": "spread", "type": "snippet", "attributes": { "fileName": "spread.md", "text": "Flattens a list, by spreading its elements into a new list.\n\nLoop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise.\n\n", "codeBlocks": { "code": "def spread(arg):\n ret = []\n for i in arg:\n if isinstance(i, list):\n ret.extend(i)\n else:\n ret.append(i)\n return ret", "example": "spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]" }, "tags": [ "list", "utility", "intermediate" ] }, "meta": { "hash": "db09a105c21df08d2d580e95dd9d3f895a38e2e9b29818f78a671203ab94df38" } }, { "id": "sum_by", "title": "sum_by", "type": "snippet", "attributes": { "fileName": "sum_by.md", "text": "Returns the sum of a list, after mapping each element to a value using the provided function.\n\nUse `map()` with `fn` to map each element to a value using the provided function, use `sum()` to return the sum of the values.\n\n", "codeBlocks": { "code": "def sum_by(lst, fn):\n return sum(map(fn,lst))", "example": "sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 20" }, "tags": [ "math", "list", "function", "beginner" ] }, "meta": { "hash": "aa4e4a8d9b99ed0e2d04af5430613f1155329592f3d4f7c2bf76a659a6df7c17" } }, { "id": "symmetric_difference", "title": "symmetric_difference", "type": "snippet", "attributes": { "fileName": "symmetric_difference.md", "text": "Returns the symmetric difference between two iterables, without filtering out duplicate values.\n\nCreate 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.\n\n", "codeBlocks": { "code": "def symmetric_difference(a, b):\n _a, _b = set(a), set(b)\n return [item for item in a if item not in _b] + [item for item in b if item not in _a]", "example": "symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "e5bb81e529740a7fbb9fe63eed33dc4ef390e7bc8c9c954a22ae3327f3d157ed" } }, { "id": "symmetric_difference_by", "title": "symmetric_difference_by", "type": "snippet", "attributes": { "fileName": "symmetric_difference_by.md", "text": "Returns the symmetric difference between two lists, after applying the provided function to each list element of both.\n\nCreate 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.\n\n", "codeBlocks": { "code": "def symmetric_difference_by(a, b, fn):\n _a, _b = set(map(fn, a)), set(map(fn, b))\n return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a]", "example": "from math import floor\nsymmetric_difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2, 3.4]" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "a3a978dbb2d7ffd0101b935484439b191fa432831f003faeefc05263eafc35e5" } }, { "id": "tail", "title": "tail", "type": "snippet", "attributes": { "fileName": "tail.md", "text": "Returns all elements in a list except for the first one.\n\nReturn `lst[1:]` if the list's length is more than `1`, otherwise, return the whole list.\n\n", "codeBlocks": { "code": "def tail(lst):\n return lst[1:] if len(lst) > 1 else lst", "example": "tail([1, 2, 3]); # [2,3]\ntail([1]); # [1]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "f06acf219bcdfbacb9e86b01f91c7d68f6f8fa8a5a043c37cf33de4969c62eae" } }, { "id": "union", "title": "union", "type": "snippet", "attributes": { "fileName": "union.md", "text": "Returns every element that exists in any of the two lists once.\n\nCreate a `set` with all values of `a` and `b` and convert to a `list`.\n\n", "codeBlocks": { "code": "def union(a,b):\n return list(set(a + b))", "example": "union([1, 2, 3], [4, 3, 2]) # [1,2,3,4]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "44b9cb979110c073c48a94d7054c8b17978f38962adbce5aa0aee794418ac7b1" } }, { "id": "union_by", "title": "union_by", "type": "snippet", "attributes": { "fileName": "union_by.md", "text": "Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.\n\nCreate 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`.\nFinally, create a `set` from the previous result and `a` and transform it into a `list`\n\n", "codeBlocks": { "code": "def union_by(a,b,fn):\n _a = set(map(fn, a))\n return list(set(a + [item for item in b if fn(item) not in _a]))", "example": "from math import floor\nunion_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]" }, "tags": [ "list", "function", "intermediate" ] }, "meta": { "hash": "3023e33e4d50e71bef58df25ceac3ed4dcb3f5027bc50868ae470654cdedc99a" } }, { "id": "unique_elements", "title": "unique_elements", "type": "snippet", "attributes": { "fileName": "unique_elements.md", "text": "Returns the unique elements in a given list.\n\nCreate a `set` from the list to discard duplicated values, then return a `list` from it.\n\n", "codeBlocks": { "code": "def unique_elements(li):\n return list(set(li))", "example": "unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4]" }, "tags": [ "list", "beginner" ] }, "meta": { "hash": "1f28461c8bbf4ce0195c756b2f013e519a43fbdef8b6a3640eafab2a6cb20bc9" } }, { "id": "values_only", "title": "values_only", "type": "snippet", "attributes": { "fileName": "values_only.md", "text": "Returns a flat list of all the values in a flat dictionary.\n\nUse `dict.values()` to return the values in the given dictionary.\nReturn a `list()` of the previous result.\n\n", "codeBlocks": { "code": "def values_only(dict):\n return list(dict.values())", "example": "ages = {\n \"Peter\": 10,\n \"Isabel\": 11,\n \"Anna\": 9,\n}\nvalues_only(ages) # [10, 11, 9]" }, "tags": [ "object", "list", "beginner" ] }, "meta": { "hash": "d6942bb96124e6cb484b2b9a6d407d761adbbe8df37339674e02a344c7bdda28" } }, { "id": "zip", "title": "zip", "type": "snippet", "attributes": { "fileName": "zip.md", "text": "Creates a list of elements, grouped based on the position in the original lists.\n\n\nUse `max` combined with `list comprehension` to get the length of the longest list in the arguments. \nLoop for `max_length` times grouping elements. \nIf lengths of `lists` vary, use `fill_value` (defaults to `None`). \n\n", "codeBlocks": { "code": "def zip(*args, fillvalue=None):\n max_length = max([len(lst) for lst in args])\n result = []\n for i in range(max_length):\n result.append([\n args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args))\n ])\n return result", "example": "zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]\nzip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]\nzip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]" }, "tags": [ "list", "math", "intermediate" ] }, "meta": { "hash": "8c0dea46f260c7edfa363a0a295683d858c2011c9220b2d4fc53025a684388f0" } } ], "meta": { "specification": "http://jsonapi.org/format/", "type": "snippetArray" } }