API Reference

All public functions are available from the main module.

import pydash

pydash.<function>

This is the recommended way to use pydash.

# OK (importing main module)
import pydash
pydash.where({})

# OK (import from main module)
from pydash import where
where({})

# NOT RECOMMENDED (importing from submodule)
from pydash.collections import where

Only the main pydash module API is guaranteed to adhere to semver. It’s possible that backwards incompatibility outside the main module API could be broken between minor releases.

py_ Instance

There is a special py_ instance available from pydash that supports method calling and method chaining from a single object:

from pydash import py_

# Method calling
py_.initial([1, 2, 3, 4, 5]) == [1, 2, 3, 4]

# Method chaining
py_([1, 2, 3, 4, 5]).initial().value() == [1, 2, 3, 4]

# Method aliasing to underscore suffixed methods that shadow builtin names
py_.map is py_.map_
py_([1, 2, 3]).map(_.to_string).value() == py_([1, 2, 3]).map_(_.to_string).value()

The py_ instance is basically a combination of using pydash.<function> and pydash.chain.

A full listing of aliased py_ methods:

Arrays

Functions that operate on lists.

New in version 1.0.0.

pydash.arrays.append(array, *items)

Push items onto the end of array and return modified array.

Parameters:
  • array (list) – List to push to.
  • items (mixed) – Items to append.
Returns:

Modified array.

Return type:

list

Warning

array is modified in place.

Example

>>> array = [1, 2, 3]
>>> push(array, 4, 5, [6])
[1, 2, 3, 4, 5, [6]]

See also

New in version 2.2.0.

pydash.arrays.cat(*arrays)[source]

Concatenates zero or more lists into one.

Parameters:arrays (list) – Lists to concatenate.
Returns:Concatenated list.
Return type:list

Example

>>> cat([1, 2], [3, 4], [[5], [6]])
[1, 2, 3, 4, [5], [6]]

New in version 2.0.0.

pydash.arrays.chunk(array, size=1)[source]

Creates a list of elements split into groups the length of size. If array can’t be split evenly, the final chunk will be the remaining elements.

Parameters:
  • array (list) – List to chunk.
  • size (int, optional) – Chunk size. Defaults to 1.
Returns:

New list containing chunks of array.

Return type:

list

Example

>>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]

New in version 1.1.0.

pydash.arrays.compact(array)[source]

Creates a list with all falsey values of array removed.

Parameters:array (list) – List to compact.
Returns:Compacted list.
Return type:list

Example

>>> compact(['', 1, 0, True, False, None])
[1, True]

New in version 1.0.0.

pydash.arrays.concat(*arrays)

Concatenates zero or more lists into one.

Parameters:arrays (list) – Lists to concatenate.
Returns:Concatenated list.
Return type:list

Example

>>> cat([1, 2], [3, 4], [[5], [6]])
[1, 2, 3, 4, [5], [6]]

New in version 2.0.0.

pydash.arrays.difference(array, *lists)[source]

Creates a list of list elements not present in the other lists.

Parameters:
  • array (list) – List to process.
  • lists (list) – Lists to check.
Returns:

Difference of the lists.

Return type:

list

Example

>>> difference([1, 2, 3], [1], [2])
[3]

New in version 1.0.0.

pydash.arrays.drop(array, n=1)[source]

Creates a slice of array with n elements dropped from the beginning.

Parameters:
  • array (list) – List to process.
  • n (int, optional) – Number of elements to drop. Defaults to 1.
Returns:

Dropped list.

Return type:

list

Example

>>> drop([1, 2, 3, 4], 2)
[3, 4]

New in version 1.0.0.

Changed in version 1.1.0: Added n argument and removed as alias of rest().

Changed in version 3.0.0: Made n default to 1.

pydash.arrays.drop_right(array, n=1)[source]

Creates a slice of array with n elements dropped from the end.

Parameters:
  • array (list) – List to process.
  • n (int, optional) – Number of elements to drop. Defaults to 1.
Returns:

Dropped list.

Return type:

list

Example

>>> drop_right([1, 2, 3, 4], 2)
[1, 2]

New in version 1.1.0.

Changed in version 3.0.0: Made n default to 1.

pydash.arrays.drop_right_while(array, callback=None)[source]

Creates a slice of array excluding elements dropped from the end. Elements are dropped until the callback returns falsey. The callback is invoked with three arguments: (value, index, array).

Parameters:
  • array (list) – List to process.
  • callback (mixed) – Callback called per iteration
Returns:

Dropped list.

Return type:

list

Example

>>> drop_right_while([1, 2, 3, 4], lambda x: x >= 3)
[1, 2]

New in version 1.1.0.

pydash.arrays.drop_while(array, callback=None)[source]

Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until the callback returns falsey. The callback is invoked with three arguments: (value, index, array).

Parameters:
  • array (list) – List to process.
  • callback (mixed) – Callback called per iteration
Returns:

Dropped list.

Return type:

list

Example

>>> drop_while([1, 2, 3, 4], lambda x: x < 3)
[3, 4]

New in version 1.1.0.

pydash.arrays.duplicates(array, callback=None)[source]

Creates a unique list of duplicate values from array. If callback is passed, each element of array is passed through a callback before duplicates are computed. The callback is invoked with three arguments: (value, index, array). If a property name is passed for callback, the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is passed for callback, the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • array (list) – List to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

List of duplicates.

Return type:

list

Example

>>> duplicates([0, 1, 3, 2, 3, 1])
[3, 1]

New in version 3.0.0.

pydash.arrays.fill(array, value, start=0, end=None)[source]

Fills elements of array with value from start up to, but not including, end.

Parameters:
  • array (list) – List to fill.
  • value (mixed) – Value to fill with.
  • start (int, optional) – Index to start filling. Defaults to 0.
  • end (int, optional) – Index to end filling. Defaults to len(array).
Returns:

Filled array.

Return type:

list

Example

>>> fill([1, 2, 3, 4, 5], 0)
[0, 0, 0, 0, 0]
>>> fill([1, 2, 3, 4, 5], 0, 1, 3)
[1, 0, 0, 4, 5]
>>> fill([1, 2, 3, 4, 5], 0, 0, 100)
[0, 0, 0, 0, 0]

Warning

array is modified in place.

New in version 3.1.0.

pydash.arrays.find_index(array, callback=None)[source]

This method is similar to pydash.collections.find(), except that it returns the index of the element that passes the callback check, instead of the element itself.

Parameters:
  • array (list) – List to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Index of found item or -1 if not found.

Return type:

int

Example

>>> find_index([1, 2, 3, 4], lambda x: x >= 3)
2
>>> find_index([1, 2, 3, 4], lambda x: x > 4)
-1

New in version 1.0.0.

pydash.arrays.find_last_index(array, callback=None)[source]

This method is similar to find_index(), except that it iterates over elements from right to left.

Parameters:
  • array (list) – List to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Index of found item or -1 if not found.

Return type:

int

Example

>>> find_last_index([1, 2, 3, 4], lambda x: x >= 3)
3
>>> find_index([1, 2, 3, 4], lambda x: x > 4)
-1

New in version 1.0.0.

pydash.arrays.first(array)[source]

Return the first element of array.

Parameters:array (list) – List to process.
Returns:First element of list.
Return type:mixed

Example

>>> first([1, 2, 3, 4])
1

See also

New in version 1.0.0.

pydash.arrays.flatten(array, is_deep=False)[source]

Flattens a nested array. If is_deep is True the array is recursively flattened, otherwise it is only flattened a single level.

Parameters:
  • array (list) – List to process.
  • is_deep (bool, optional) – Whether to recursively flatten array.
Returns:

Flattened list.

Return type:

list

Example

>>> flatten([[1], [2, [3]], [[4]]])
[1, 2, [3], [4]]
>>> flatten([[1], [2, [3]], [[4]]], True)
[1, 2, 3, 4]

New in version 1.0.0.

Changed in version 2.0.0: Removed callback option. Added is_deep option. Made it shallow by default.

pydash.arrays.flatten_deep(array)[source]

Flattens a nested array recursively. This is the same as calling flatten(array, is_deep=True).

Parameters:array (list) – List to process.
Returns:Flattened list.
Return type:list

Example

>>> flatten_deep([[1], [2, [3]], [[4]]])
[1, 2, 3, 4]

New in version 2.0.0.

pydash.arrays.head(array)

Return the first element of array.

Parameters:array (list) – List to process.
Returns:First element of list.
Return type:mixed

Example

>>> first([1, 2, 3, 4])
1

See also

New in version 1.0.0.

pydash.arrays.index_of(array, value, from_index=0)[source]

Gets the index at which the first occurrence of value is found.

Parameters:
  • array (list) – List to search.
  • value (mixed) – Value to search for.
  • from_index (int, optional) – Index to search from.
Returns:

Index of found item or -1 if not found.

Return type:

int

Example

>>> index_of([1, 2, 3, 4], 2)
1
>>> index_of([2, 1, 2, 3], 2, from_index=1)
2

New in version 1.0.0.

pydash.arrays.initial(array)[source]

Return all but the last element of array.

Parameters:array (list) – List to process.
Returns:Initial part of array.
Return type:list

Example

>>> initial([1, 2, 3, 4])
[1, 2, 3]

New in version 1.0.0.

pydash.arrays.intercalate(array, separator)[source]

Like intersperse() for lists of lists but shallowly flattening the result.

Parameters:
  • array (list) – List to intercalate.
  • separator (mixed) – Element to insert.
Returns:

Intercalated list.

Return type:

list

Example

>>> intercalate([1, [2], [3], 4], 'x')
[1, 'x', 2, 'x', 3, 'x', 4]

New in version 2.0.0.

pydash.arrays.interleave(*arrays)[source]

Merge multiple lists into a single list by inserting the next element of each list by sequential round-robin into the new list.

Parameters:arrays (list) – Lists to interleave.
Retruns:
list: Interleaved list.

Example

>>> interleave([1, 2, 3], [4, 5, 6], [7, 8, 9])
[1, 4, 7, 2, 5, 8, 3, 6, 9]

New in version 2.0.0.

pydash.arrays.intersection(*arrays)[source]

Computes the intersection of all the passed-in arrays.

Parameters:arrays (list) – Lists to process.
Returns:Intersection of provided lists.
Return type:list

Example

>>> intersection([1, 2, 3], [1, 2, 3, 4, 5])
[1, 2, 3]

New in version 1.0.0.

pydash.arrays.intersperse(array, separator)[source]

Insert a separating element between the elements of array.

Parameters:
  • array (list) – List to intersperse.
  • separator (mixed) – Element to insert.
Returns:

Interspersed list.

Return type:

list

Example

>>> intersperse([1, [2], [3], 4], 'x')
[1, 'x', [2], 'x', [3], 'x', 4]

New in version 2.0.0.

pydash.arrays.last(array)[source]

Return the last element of array.

Parameters:array (list) – List to process.
Returns:Last part of array.
Return type:mixed

Example

>>> last([1, 2, 3, 4])
4

New in version 1.0.0.

pydash.arrays.last_index_of(array, value, from_index=None)[source]

Gets the index at which the last occurrence of value is found.

Parameters:
  • array (list) – List to search.
  • value (mixed) – Value to search for.
  • from_index (int, optional) – Index to search from.
Returns:

Index of found item or False if not found.

Return type:

int

Example

>>> last_index_of([1, 2, 2, 4], 2)
2
>>> last_index_of([1, 2, 2, 4], 2, from_index=1)
1

New in version 1.0.0.

pydash.arrays.mapcat(array, callback=None)[source]

Map a callback to each element of a list and concatenate the results into a single list using cat().

Parameters:
  • array (list) – List to map and concatenate.
  • callback (mixed) – Callback to apply to each element.
Returns:

Mapped and concatenated list.

Return type:

list

Example

>>> mapcat(range(4), lambda x: list(range(x)))
[0, 0, 1, 0, 1, 2]

New in version 2.0.0.

pydash.arrays.object_(keys, values=None)

Creates a dict composed from lists of keys and values. Pass either a single two dimensional list, i.e. [[key1, value1], [key2, value2]], or two lists, one of keys and one of corresponding values.

Parameters:
  • keys (list) – Either a list of keys or a list of [key, value] pairs
  • values (list, optional) – List of values to zip
Returns:

Zipped dict.

Return type:

dict

Example

>>> zip_object([1, 2, 3], [4, 5, 6])
{1: 4, 2: 5, 3: 6}

See also

New in version 1.0.0.

pydash.arrays.pull(array, *values)[source]

Removes all provided values from the given array.

Parameters:
  • array (list) – List to pull from.
  • values (mixed) – Values to remove.
Returns:

Modified array.

Return type:

list

Warning

array is modified in place.

Example

>>> pull([1, 2, 2, 3, 3, 4], 2, 3)
[1, 4]

New in version 1.0.0.

pydash.arrays.pull_at(array, *indexes)[source]

Removes elements from array corresponding to the specified indexes and returns a list of the removed elements. Indexes may be specified as a list of indexes or as individual arguments.

Parameters:
  • array (list) – List to pull from.
  • indexes (int) – Indexes to pull.
Returns:

Modified array.

Return type:

list

Warning

array is modified in place.

Example

>>> pull_at([1, 2, 3, 4], 0, 2)
[2, 4]

New in version 1.1.0.

pydash.arrays.push(array, *items)[source]

Push items onto the end of array and return modified array.

Parameters:
  • array (list) – List to push to.
  • items (mixed) – Items to append.
Returns:

Modified array.

Return type:

list

Warning

array is modified in place.

Example

>>> array = [1, 2, 3]
>>> push(array, 4, 5, [6])
[1, 2, 3, 4, 5, [6]]

See also

New in version 2.2.0.

pydash.arrays.remove(array, callback=None)[source]

Removes all elements from a list that the callback returns truthy for and returns an array of removed elements.

Parameters:
  • array (list) – List to remove elements from.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Removed elements of array.

Return type:

list

Warning

array is modified in place.

Example

>>> array = [1, 2, 3, 4]
>>> items = remove(array, lambda x: x >= 3)
>>> items
[3, 4]
>>> array
[1, 2]

New in version 1.0.0.

pydash.arrays.rest(array)[source]

Return all but the first element of array.

Parameters:array (list) – List to process.
Returns:Rest of the list.
Return type:list

Example

>>> rest([1, 2, 3, 4])
[2, 3, 4]

See also

New in version 1.0.0.

pydash.arrays.reverse(array)[source]

Return array in reverse order.

Parameters:array (list|string) – Object to process.
Returns:Reverse of object.
Return type:list|string

Example

>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]

New in version 2.2.0.

pydash.arrays.shift(array)[source]

Remove the first element of array and return it.

Parameters:array (list) – List to shift.
Returns:First element of array.
Return type:mixed

Warning

array is modified in place.

Example

>>> array = [1, 2, 3, 4]
>>> item = shift(array)
>>> item
1
>>> array
[2, 3, 4]

New in version 2.2.0.

pydash.arrays.slice_(array, start=0, end=None)[source]

Slices array from the start index up to, but not including, the end index.

Parameters:
  • array (list) – Array to slice.
  • start (int, optional) – Start index. Defaults to 0.
  • end (int, optional) – End index. Defaults to selecting the value at start index.
Returns:

Sliced list.

Return type:

list

Example

>>> slice_([1, 2, 3, 4])
[1]
>>> slice_([1, 2, 3, 4], 1)
[2]
>>> slice_([1, 2, 3, 4], 1, 3)
[2, 3]

New in version 1.1.0.

pydash.arrays.sort(array, comparison=None, key=None, reverse=False)[source]

Sort array using optional comparison, key, and reverse options and return sorted array.

Note

Python 3 removed the option to pass a custom comparison function and instead only allows a key function. Therefore, if a comparison function is passed in, it will be converted to a key function automatically using functools.cmp_to_key.

Parameters:
  • array (list) – List to sort.
  • comparison (callable, optional) – A custom comparison function used to sort the list. Function should accept two arguments and return a negative, zero, or position number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Defaults to None. This argument is mutually exclusive with key.
  • key (callback, optional) – A function of one argument used to extract a a comparison key from each list element. Defaults to None. This argument is mutually exclusive with comparison.
  • reverse (bool, optional) – Whether to reverse the sort. Defaults to False.
Returns:

Sorted list.

Return type:

list

Warning

array is modified in place.

Example

>>> sort([2, 1, 4, 3])
[1, 2, 3, 4]
>>> sort([2, 1, 4, 3], reverse=True)
[4, 3, 2, 1]
>>> results = sort([{'a': 2, 'b': 1},                            {'a': 3, 'b': 2},                            {'a': 0, 'b': 3}],                           key=lambda item: item['a'])
>>> assert results == [{'a': 0, 'b': 3},                               {'a': 2, 'b': 1},                               {'a': 3, 'b': 2}]

New in version 2.2.0.

pydash.arrays.sorted_index(array, value, callback=None)[source]

Determine the smallest index at which value should be inserted into array in order to maintain the sort order of the sorted array. If callback is passed, it will be executed for value and each element in array to compute their sort ranking. The callback is invoked with one argument: (value). If a property name is passed for callback, the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is passed for callback, the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • array (list) – List to inspect.
  • value (mixed) – Value to evaluate.
  • callback (mixed, optional) – Callback to determine sort key.
Returns:

Smallest index.

Return type:

int

Example

>>> sorted_index([1, 2, 2, 3, 4], 2)
1

New in version 1.0.0.

pydash.arrays.sorted_last_index(array, value, callback=None)[source]

This method is like sorted_index() except that it returns the highest index at which a value should be inserted into a given sorted array in order to maintain the sort order of the array.

Parameters:
  • array (list) – List to inspect.
  • value (mixed) – Value to evaluate.
  • callback (mixed, optional) – Callback to determine sort key.
Returns:

Highest index.

Return type:

int

Example

>>> sorted_last_index([1, 2, 2, 3, 4], 2)
3

New in version 1.1.0.

pydash.arrays.splice(array, index, how_many=None, *items)[source]

Modify the contents of array by inserting elements starting at index and removing how_many number of elements after index.

Parameters:
  • array (list|str) – List to splice.
  • index (int) – Index to splice at.
  • how_many (int, optional) – Number of items to remove starting at index. If None then all items after index are removed. Defaults to None.
  • items (mixed) – Elements to insert starting at index. Each item is inserted in the order given.
Returns:

The removed elements of array or the spliced string.

Return type:

list|str

Warning

array is modified in place if list.

Example

>>> array = [1, 2, 3, 4]
>>> splice(array, 1)
[2, 3, 4]
>>> array
[1]
>>> array = [1, 2, 3, 4]
>>> splice(array, 1, 2)
[2, 3]
>>> array
[1, 4]
>>> array = [1, 2, 3, 4]
>>> splice(array, 1, 2, 0, 0)
[2, 3]
>>> array
[1, 0, 0, 4]

New in version 2.2.0.

Changed in version 3.0.0: Support string splicing.

pydash.arrays.split_at(array, index)[source]

Returns a list of two lists composed of the split of array at index.

Parameters:
  • array (list) – List to split.
  • index (int) – Index to split at.
Returns:

Split list.

Return type:

list

Example

>>> split_at([1, 2, 3, 4], 2)
[[1, 2], [3, 4]]

New in version 2.0.0.

pydash.arrays.tail(array)

Return all but the first element of array.

Parameters:array (list) – List to process.
Returns:Rest of the list.
Return type:list

Example

>>> rest([1, 2, 3, 4])
[2, 3, 4]

See also

New in version 1.0.0.

pydash.arrays.take(array, n=1)[source]

Creates a slice of array with n elements taken from the beginning.

Parameters:
  • array (list) – List to process.
  • n (int, optional) – Number of elements to take. Defaults to 1.
Returns:

Taken list.

Return type:

list

Example

>>> take([1, 2, 3, 4], 2)
[1, 2]

New in version 1.0.0.

Changed in version 1.1.0: Added n argument and removed as alias of first().

Changed in version 3.0.0: Made n default to 1.

pydash.arrays.take_right(array, n=1)[source]

Creates a slice of array with n elements taken from the end.

Parameters:
  • array (list) – List to process.
  • n (int, optional) – Number of elements to take. Defaults to 1.
Returns:

Taken list.

Return type:

list

Example

>>> take_right([1, 2, 3, 4], 2)
[3, 4]

New in version 1.1.0.

Changed in version 3.0.0: Made n default to 1.

pydash.arrays.take_right_while(array, callback=None)[source]

Creates a slice of array with elements taken from the end. Elements are taken until the callback returns falsey. The callback is invoked with three arguments: (value, index, array).

Parameters:
  • array (list) – List to process.
  • callback (mixed) – Callback called per iteration
Returns:

Dropped list.

Return type:

list

Example

>>> take_right_while([1, 2, 3, 4], lambda x: x >= 3)
[3, 4]

New in version 1.1.0.

pydash.arrays.take_while(array, callback=None)[source]

Creates a slice of array with elements taken from the beginning. Elements are taken until the callback returns falsey. The callback is invoked with three arguments: (value, index, array).

Parameters:
  • array (list) – List to process.
  • callback (mixed) – Callback called per iteration
Returns:

Taken list.

Return type:

list

Example

>>> take_while([1, 2, 3, 4], lambda x: x < 3)
[1, 2]

New in version 1.1.0.

pydash.arrays.union(*arrays)[source]

Computes the union of the passed-in arrays.

Parameters:arrays (list) – Lists to unionize.
Returns:Unionized list.
Return type:list

Example

>>> union([1, 2, 3], [2, 3, 4], [3, 4, 5])
[1, 2, 3, 4, 5]

New in version 1.0.0.

pydash.arrays.uniq(array, callback=None)[source]

Creates a duplicate-value-free version of the array. If callback is passed, each element of array is passed through a callback before uniqueness is computed. The callback is invoked with three arguments: (value, index, array). If a property name is passed for callback, the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is passed for callback, the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • array (list) – List to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Unique list.

Return type:

list

Example

>>> uniq([1, 2, 3, 1, 2, 3])
[1, 2, 3]

See also

New in version 1.0.0.

pydash.arrays.unique(array, callback=None)

Creates a duplicate-value-free version of the array. If callback is passed, each element of array is passed through a callback before uniqueness is computed. The callback is invoked with three arguments: (value, index, array). If a property name is passed for callback, the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is passed for callback, the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • array (list) – List to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Unique list.

Return type:

list

Example

>>> uniq([1, 2, 3, 1, 2, 3])
[1, 2, 3]

See also

New in version 1.0.0.

pydash.arrays.unshift(array, *items)[source]

Insert the given elements at the beginning of array and return the modified list.

Parameters:
  • array (list) – List to modify.
  • items (mixed) – Items to insert.
Returns:

Modified list.

Return type:

list

Warning

array is modified in place.

Example

>>> array = [1, 2, 3, 4]
>>> unshift(array, -1, -2)
[-1, -2, 1, 2, 3, 4]
>>> array
[-1, -2, 1, 2, 3, 4]

New in version 2.2.0.

pydash.arrays.unzip(array)[source]

The inverse of zip_(), this method splits groups of elements into lists composed of elements from each group at their corresponding indexes.

Parameters:array (list) – List to process.
Returns:Unzipped list.
Return type:list

Example

>>> unzip([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

New in version 1.0.0.

pydash.arrays.unzip_with(array, callback=None)[source]

This method is like unzip() except that it accepts a callback to specify how regrouped values should be combined. The callback is invoked with four arguments: (accumulator, value, index, group).

Parameters:
  • array (list) – List to process.
  • callback (callable, optional) – Function to combine regrouped values.
Returns:

Unzipped list.

Return type:

list

Example

>>> from pydash import add
>>> unzip_with([[1, 10, 100], [2, 20, 200]], add)
[3, 30, 300]

New in version 3.3.0.

pydash.arrays.without(array, *values)[source]

Creates an array with all occurrences of the passed values removed.

Parameters:
  • array (list) – List to filter.
  • values (mixed) – Values to remove.
Returns:

Filtered list.

Return type:

list

Example

>>> without([1, 2, 3, 2, 4, 4], 2, 4)
[1, 3]

New in version 1.0.0.

pydash.arrays.xor(array, *lists)[source]

Creates a list that is the symmetric difference of the provided lists.

Parameters:
  • array (list) – List to process.
  • *lists (list) – Lists to xor with.
Returns:

XOR’d list.

Return type:

list

Example

>>> xor([1, 3, 4], [1, 2, 4], [2])
[3]

New in version 1.0.0.

pydash.arrays.zip_(*arrays)[source]

Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes.

Parameters:arrays (list) – Lists to process.
Returns:Zipped list.
Return type:list

Example

>>> zip_([1, 2, 3], [4, 5, 6], [7, 8, 9])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

New in version 1.0.0.

pydash.arrays.zip_object(keys, values=None)[source]

Creates a dict composed from lists of keys and values. Pass either a single two dimensional list, i.e. [[key1, value1], [key2, value2]], or two lists, one of keys and one of corresponding values.

Parameters:
  • keys (list) – Either a list of keys or a list of [key, value] pairs
  • values (list, optional) – List of values to zip
Returns:

Zipped dict.

Return type:

dict

Example

>>> zip_object([1, 2, 3], [4, 5, 6])
{1: 4, 2: 5, 3: 6}

See also

New in version 1.0.0.

pydash.arrays.zip_with(*arrays, **kargs)[source]

This method is like zip() except that it accepts a callback to specify how grouped values should be combined. The callback is invoked with four arguments: (accumulator, value, index, group).

Parameters:
  • *arrays (list) – Lists to process.
  • callback (function) – Function to combine grouped values.
Returns:

Zipped list of grouped elements.

Return type:

list

Example

>>> from pydash import add
>>> zip_with([1, 2], [10, 20], [100, 200], add)
[111, 222]
>>> zip_with([1, 2], [10, 20], [100, 200], callback=add)
[111, 222]

New in version 3.3.0.

Chaining

Method chaining interface.

New in version 1.0.0.

pydash.chaining.chain(value=<pydash.helpers._NoValue object>)[source]

Creates a Chain object which wraps the given value to enable intuitive method chaining. Chaining is lazy and won’t compute a final value until Chain.value() is called.

Parameters:value (mixed) – Value to initialize chain operations with.
Returns:Instance of Chain initialized with value.
Return type:Chain

Example

>>> chain([1, 2, 3, 4]).map(lambda x: x * 2).sum().value()
20
>>> chain().map(lambda x: x * 2).sum()([1, 2, 3, 4])
20
>>> summer = chain([1, 2, 3, 4]).sum()
>>> new_summer = summer.plant([1, 2])
>>> new_summer.value()
3
>>> summer.value()
10
>>> def echo(item): print(item)
>>> summer = chain([1, 2, 3, 4]).each(echo).sum()
>>> committed = summer.commit()
1
2
3
4
>>> committed.value()
10
>>> summer.value()
1
2
3
4
10

New in version 1.0.0.

Changed in version 2.0.0: Made chaining lazy.

Changed in version 3.0.0: - Added support for late passing of value. - Added Chain.plant() for replacing initial chain value. - Added Chain.commit() for returning a new Chain instance initialized with the results from calling Chain.value().

pydash.chaining.tap(value, interceptor)[source]

Invokes interceptor with the value as the first argument and then returns value. The purpose of this method is to “tap into” a method chain in order to perform operations on intermediate results within the chain.

Parameters:
  • value (mixed) – Current value of chain operation.
  • interceptor (function) – Function called on value.
Returns:

value after interceptor call.

Return type:

mixed

Example

>>> data = []
>>> def log(value): data.append(value)
>>> chain([1, 2, 3, 4]).map(lambda x: x * 2).tap(log).value()
[2, 4, 6, 8]
>>> data
[[2, 4, 6, 8]]

New in version 1.0.0.

pydash.chaining.thru(value, interceptor)[source]

Returns the result of calling interceptor on value. The purpose of this method is to pass value through a function during a method chain.

Parameters:
  • value (mixed) – Current value of chain operation.
  • interceptor (function) – Function called with value.
Returns:

Results of interceptor(value).

Return type:

mixed

Example

>>> chain([1, 2, 3, 4]).thru(lambda x: x * 2).value()
[1, 2, 3, 4, 1, 2, 3, 4]

New in version 2.0.0.

Collections

Functions that operate on lists and dicts.

New in version 1.0.0.

pydash.collections.all_(collection, callback=None)

Checks if the callback returns a truthy value for all elements of a collection. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Whether all elements are truthy.

Return type:

bool

Example

>>> every([1, True, 'hello'])
True
>>> every([1, False, 'hello'])
False
>>> every([{'a': 1}, {'a': True}, {'a': 'hello'}], 'a')
True
>>> every([{'a': 1}, {'a': False}, {'a': 'hello'}], 'a')
False
>>> every([{'a': 1}, {'a': 1}], {'a': 1})
True
>>> every([{'a': 1}, {'a': 2}], {'a': 1})
False

See also

New in version 1.0.0.

pydash.collections.any_(collection, callback=None)

Checks if the callback returns a truthy value for any element of a collection. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callbacked (mixed, optional) – Callback applied per iteration.
Returns:

Whether any of the elements are truthy.

Return type:

bool

Example

>>> some([False, True, 0])
True
>>> some([False, 0, None])
False
>>> some([1, 2, 3, 4], lambda x: x >= 3)
True
>>> some([1, 2, 3, 4], lambda x: x == 0)
False

See also

New in version 1.0.0.

pydash.collections.at(collection, *indexes)[source]

Creates a list of elements from the specified indexes, or keys, of the collection. Indexes may be specified as individual arguments or as arrays of indexes.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • indexes (mixed) – The indexes of collection to retrieve, specified as individual indexes or arrays of indexes.
Returns:

filtered list

Return type:

list

Example

>>> at([1, 2, 3, 4], 0, 2)
[1, 3]
>>> at({'a': 1, 'b': 2, 'c': 3, 'd': 4}, 'a', 'c')
[1, 3]

New in version 1.0.0.

pydash.collections.collect(collection, callback=None)

Creates an array of values by running each element in the collection through the callback. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Mapped list.

Return type:

list

Example

>>> map_([1, 2, 3, 4], str)
['1', '2', '3', '4']

See also

New in version 1.0.0.

pydash.collections.contains(collection, target, from_index=0)[source]

Checks if a given value is present in a collection. If from_index is negative, it is used as the offset from the end of the collection.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • target (mixed) – Target value to compare to.
  • from_index (int, optional) – Offset to start search from.
Returns:

Whether target is in collection.

Return type:

bool

Example

>>> contains([1, 2, 3, 4], 2)
True
>>> contains([1, 2, 3, 4], 2, from_index=2)
False
>>> contains({'a': 1, 'b': 2, 'c': 3, 'd': 4}, 2)
True

See also

New in version 1.0.0.

pydash.collections.count_by(collection, callback=None)[source]

Creates an object composed of keys generated from the results of running each element of collection through the callback.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Dict containing counts by key.

Return type:

dict

Example

>>> results = count_by([1, 2, 1, 2, 3, 4])
>>> assert results == {1: 2, 2: 2, 3: 1, 4: 1}
>>> results = count_by(['a', 'A', 'B', 'b'], lambda x: x.lower())
>>> assert results == {'a': 2, 'b': 2}
>>> results = count_by({'a': 1, 'b': 1, 'c': 3, 'd': 3})
>>> assert results == {1: 2, 3: 2}

New in version 1.0.0.

pydash.collections.deep_pluck(collection, path)[source]

Like pluck but works with deep paths.

Parameters:
  • collection (list|dict) – list of dicts
  • path (str|list) – collection’s path to pluck
Returns:

plucked list

Return type:

list

Example

>>> deep_pluck([[[0, 1]], [[2, 3]], [[4, 5]]], '0.1')
[1, 3, 5]
>>> deep_pluck([{'a': {'b': 1}}, {'a': {'b': 2}}], 'a.b')
[1, 2]
>>> deep_pluck([{'a': {'b': [0, 1]}}, {'a': {'b': [2, 3]}}], 'a.b.1')
[1, 3]

New in version 2.2.0.

pydash.collections.detect(collection, callback=None)

Iterates over elements of a collection, returning the first element that the callback returns truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

First element found or None.

Return type:

mixed

Example

>>> find([1, 2, 3, 4], lambda x: x >= 3)
3
>>> find([{'a': 1}, {'b': 2}, {'a': 1, 'b': 2}], {'a': 1})
{'a': 1}

See also

New in version 1.0.0.

pydash.collections.each(collection, callback=None)

Iterates over elements of a collection, executing the callback for each element.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

collection

Return type:

list|dict

Example

>>> results = {}
>>> def cb(x): results[x] = x ** 2
>>> each([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> assert results == {1: 1, 2: 4, 3: 9, 4: 16}

See also

New in version 1.0.0.

pydash.collections.each_right(collection, callback)

This method is like for_each() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

collection

Return type:

list|dict

Example

>>> results = {'total': 1}
>>> def cb(x): results['total'] = x * results['total']
>>> each_right([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> assert results == {'total': 24}

See also

New in version 1.0.0.

pydash.collections.every(collection, callback=None)[source]

Checks if the callback returns a truthy value for all elements of a collection. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Whether all elements are truthy.

Return type:

bool

Example

>>> every([1, True, 'hello'])
True
>>> every([1, False, 'hello'])
False
>>> every([{'a': 1}, {'a': True}, {'a': 'hello'}], 'a')
True
>>> every([{'a': 1}, {'a': False}, {'a': 'hello'}], 'a')
False
>>> every([{'a': 1}, {'a': 1}], {'a': 1})
True
>>> every([{'a': 1}, {'a': 2}], {'a': 1})
False

See also

New in version 1.0.0.

pydash.collections.filter_(collection, callback=None)[source]

Iterates over elements of a collection, returning a list of all elements the callback returns truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Filtered list.

Return type:

list

Example

>>> results = filter_([{'a': 1}, {'b': 2}, {'a': 1, 'b': 3}], {'a': 1})
>>> assert results == [{'a': 1}, {'a': 1, 'b': 3}]
>>> filter_([1, 2, 3, 4], lambda x: x >= 3)
[3, 4]

See also

New in version 1.0.0.

pydash.collections.find(collection, callback=None)[source]

Iterates over elements of a collection, returning the first element that the callback returns truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

First element found or None.

Return type:

mixed

Example

>>> find([1, 2, 3, 4], lambda x: x >= 3)
3
>>> find([{'a': 1}, {'b': 2}, {'a': 1, 'b': 2}], {'a': 1})
{'a': 1}

See also

New in version 1.0.0.

pydash.collections.find_last(collection, callback=None)[source]

This method is like find() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Last element found or None.

Return type:

mixed

Example

>>> find_last([1, 2, 3, 4], lambda x: x >= 3)
4
>>> results = find_last([{'a': 1}, {'b': 2}, {'a': 1, 'b': 2}],                                 {'a': 1})
>>> assert results == {'a': 1, 'b': 2}

New in version 1.0.0.

pydash.collections.find_where(collection, callback=None)

Iterates over elements of a collection, returning the first element that the callback returns truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

First element found or None.

Return type:

mixed

Example

>>> find([1, 2, 3, 4], lambda x: x >= 3)
3
>>> find([{'a': 1}, {'b': 2}, {'a': 1, 'b': 2}], {'a': 1})
{'a': 1}

See also

New in version 1.0.0.

pydash.collections.foldl(collection, callback=None, accumulator=None)

Reduces a collection to a value which is the accumulated result of running each element in the collection through the callback, where each successive callback execution consumes the return value of the previous execution.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Accumulator object containing results of reduction.

Return type:

mixed

Example

>>> reduce_([1, 2, 3, 4], lambda total, x: total * x)
24

See also

New in version 1.0.0.

pydash.collections.foldr(collection, callback=None, accumulator=None)

This method is like reduce_() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Accumulator object containing results of reduction.

Return type:

mixed

Example

>>> reduce_right([1, 2, 3, 4], lambda total, x: total ** x)
4096

See also

New in version 1.0.0.

Changed in version 3.2.1: Fix bug where collection was not reversed correctly.

pydash.collections.for_each(collection, callback=None)[source]

Iterates over elements of a collection, executing the callback for each element.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

collection

Return type:

list|dict

Example

>>> results = {}
>>> def cb(x): results[x] = x ** 2
>>> each([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> assert results == {1: 1, 2: 4, 3: 9, 4: 16}

See also

New in version 1.0.0.

pydash.collections.for_each_right(collection, callback)[source]

This method is like for_each() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

collection

Return type:

list|dict

Example

>>> results = {'total': 1}
>>> def cb(x): results['total'] = x * results['total']
>>> each_right([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> assert results == {'total': 24}

See also

New in version 1.0.0.

pydash.collections.group_by(collection, callback=None)[source]

Creates an object composed of keys generated from the results of running each element of a collection through the callback.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Results of grouping by callback.

Return type:

dict

Example

>>> results = group_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], 'a')
>>> assert results == {1: [{'a': 1, 'b': 2}], 3: [{'a': 3, 'b': 4}]}
>>> results = group_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], {'a': 1})
>>> assert results == {False: [{'a': 3, 'b': 4}],                               True: [{'a': 1, 'b': 2}]}

New in version 1.0.0.

pydash.collections.include(collection, target, from_index=0)

Checks if a given value is present in a collection. If from_index is negative, it is used as the offset from the end of the collection.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • target (mixed) – Target value to compare to.
  • from_index (int, optional) – Offset to start search from.
Returns:

Whether target is in collection.

Return type:

bool

Example

>>> contains([1, 2, 3, 4], 2)
True
>>> contains([1, 2, 3, 4], 2, from_index=2)
False
>>> contains({'a': 1, 'b': 2, 'c': 3, 'd': 4}, 2)
True

See also

New in version 1.0.0.

pydash.collections.index_by(collection, callback=None)[source]

Creates an object composed of keys generated from the results of running each element of the collection through the given callback.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Results of indexing by callback.

Return type:

dict

Example

>>> results = index_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], 'a')
>>> assert results == {1: {'a': 1, 'b': 2}, 3: {'a': 3, 'b': 4}}

New in version 1.0.0.

pydash.collections.inject(collection, callback=None, accumulator=None)

Reduces a collection to a value which is the accumulated result of running each element in the collection through the callback, where each successive callback execution consumes the return value of the previous execution.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Accumulator object containing results of reduction.

Return type:

mixed

Example

>>> reduce_([1, 2, 3, 4], lambda total, x: total * x)
24

See also

New in version 1.0.0.

pydash.collections.invoke(collection, method_name, *args, **kargs)[source]

Invokes the method named by method_name on each element in the collection returning a list of the results of each invoked method.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • method_name (str) – Name of method to invoke.
  • args (optional) – Arguments to pass to method call.
  • kargs (optional) – Keyword arguments to pass to method call.
Returns:

List of results of invoking method of each item.

Return type:

list

Example

>>> items = [[1, 2], [2, 3], [3, 4]]
>>> invoke(items, 'pop')
[2, 3, 4]
>>> items
[[1], [2], [3]]
>>> items = [[1, 2], [2, 3], [3, 4]]
>>> invoke(items, 'pop', 0)
[1, 2, 3]
>>> items
[[2], [3], [4]]

New in version 1.0.0.

pydash.collections.map_(collection, callback=None)[source]

Creates an array of values by running each element in the collection through the callback. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Mapped list.

Return type:

list

Example

>>> map_([1, 2, 3, 4], str)
['1', '2', '3', '4']

See also

New in version 1.0.0.

pydash.collections.mapiter(collection, callback=None)[source]

Like map_() except returns a generator.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Each mapped item.

Return type:

generator

Example

>>> gen = mapiter([1, 2, 3, 4], str)
>>> next(gen)
'1'
>>> next(gen)
'2'
>>> list(gen)
['3', '4']

New in version 2.1.0.

pydash.collections.max_(collection, callback=None, default=<pydash.helpers._NoValue object>)[source]

Retrieves the maximum value of a collection.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
  • default – default value when collection is empty
Returns:

Maximum value.

Return type:

mixed

Example

>>> max_([1, 2, 3, 4])
4
>>> max_([{'a': 1}, {'a': 2}, {'a': 3}], 'a')
{'a': 3}
>>> max_([], default=-1)
-1

New in version 1.0.0.

pydash.collections.min_(collection, callback=None, default=<pydash.helpers._NoValue object>)[source]

Retrieves the minimum value of a collection.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Minimum value.

Return type:

mixed

Example

>>> min_([1, 2, 3, 4])
1
>>> min_([{'a': 1}, {'a': 2}, {'a': 3}], 'a')
{'a': 1}
>>> min_([], default=100)
100

New in version 1.0.0.

pydash.collections.partition(collection, callback=None)[source]

Creates an array of elements split into two groups, the first of which contains elements the callback returns truthy for, while the second of which contains elements the callback returns falsey for. The callback is invoked with three arguments: (value, index|key, collection).

If a property name is provided for callback the created pluck() style callback returns the property value of the given element.

If an object is provided for callback the created where() style callback returns True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

List of grouped elements.

Return type:

list

Example

>>> partition([1, 2, 3, 4], lambda x: x >= 3)
[[3, 4], [1, 2]]

New in version 1.1.0.

pydash.collections.pluck(collection, key)[source]

Retrieves the value of a specified property from all elements in the collection.

Parameters:
  • collection (list) – List of dicts.
  • key (str) – Collection’s key to pluck.
Returns:

Plucked list.

Return type:

list

Example

>>> pluck([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], 'a')
[1, 3, 5]

New in version 1.0.0.

pydash.collections.reduce_(collection, callback=None, accumulator=None)[source]

Reduces a collection to a value which is the accumulated result of running each element in the collection through the callback, where each successive callback execution consumes the return value of the previous execution.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Accumulator object containing results of reduction.

Return type:

mixed

Example

>>> reduce_([1, 2, 3, 4], lambda total, x: total * x)
24

See also

New in version 1.0.0.

pydash.collections.reduce_right(collection, callback=None, accumulator=None)[source]

This method is like reduce_() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Accumulator object containing results of reduction.

Return type:

mixed

Example

>>> reduce_right([1, 2, 3, 4], lambda total, x: total ** x)
4096

See also

New in version 1.0.0.

Changed in version 3.2.1: Fix bug where collection was not reversed correctly.

pydash.collections.reductions(collection, callback=None, accumulator=None, from_right=False)[source]

This function is like reduce_() except that it returns a list of every intermediate value in the reduction operation.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Results of each reduction operation.

Return type:

list

Example

>>> reductions([1, 2, 3, 4], lambda total, x: total * x)
[2, 6, 24]

Note

The last element of the returned list would be the result of using reduce_().

New in version 2.0.0.

pydash.collections.reductions_right(collection, callback=None, accumulator=None)[source]

This method is like reductions() except that it iterates over elements of a collection from right to left.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Initial value of aggregator. Default is to use the result of the first iteration.
Returns:

Results of each reduction operation.

Return type:

list

Example

>>> reductions_right([1, 2, 3, 4], lambda total, x: total ** x)
[64, 4096, 4096]

Note

The last element of the returned list would be the result of using reduce_().

New in version 2.0.0.

pydash.collections.reject(collection, callback=None)[source]

The opposite of filter_() this method returns the elements of a collection that the callback does not return truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Rejected elements of collection.

Return type:

list

Example

>>> reject([1, 2, 3, 4], lambda x: x >= 3)
[1, 2]
>>> reject([{'a': 0}, {'a': 1}, {'a': 2}], 'a')
[{'a': 0}]
>>> reject([{'a': 0}, {'a': 1}, {'a': 2}], {'a': 1})
[{'a': 0}, {'a': 2}]

New in version 1.0.0.

pydash.collections.sample(collection, n=None)[source]

Retrieves a random element or n random elements from a collection.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • n (int, optional) – Number of random samples to return.
Returns:

List of sampled collection value if n is provided, else single value from collection if n is None.

Return type:

list|mixed

Example

>>> items = [1, 2, 3, 4, 5]
>>> results = sample(items, 2)
>>> assert len(results) == 2
>>> assert set(items).intersection(results) == set(results)

New in version 1.0.0.

pydash.collections.select(collection, callback=None)

Iterates over elements of a collection, returning a list of all elements the callback returns truthy for.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Filtered list.

Return type:

list

Example

>>> results = filter_([{'a': 1}, {'b': 2}, {'a': 1, 'b': 3}], {'a': 1})
>>> assert results == [{'a': 1}, {'a': 1, 'b': 3}]
>>> filter_([1, 2, 3, 4], lambda x: x >= 3)
[3, 4]

See also

New in version 1.0.0.

pydash.collections.shuffle(collection)[source]

Creates a list of shuffled values, using a version of the Fisher-Yates shuffle.

Parameters:collection (list|dict) – Collection to iterate over.
Returns:Shuffled list of values.
Return type:list

Example

>>> items = [1, 2, 3, 4]
>>> results = shuffle(items)
>>> assert len(results) == len(items)
>>> assert set(results) == set(items)

New in version 1.0.0.

pydash.collections.size(collection)[source]

Gets the size of the collection by returning len(collection) for iterable objects.

Parameters:collection (list|dict) – Collection to iterate over.
Returns:Collection length.
Return type:int

Example

>>> size([1, 2, 3, 4])
4

New in version 1.0.0.

pydash.collections.some(collection, callback=None)[source]

Checks if the callback returns a truthy value for any element of a collection. The callback is invoked with three arguments: (value, index|key, collection). If a property name is passed for callback, the created pluck() style callback will return the property value of the given element. If an object is passed for callback, the created where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callbacked (mixed, optional) – Callback applied per iteration.
Returns:

Whether any of the elements are truthy.

Return type:

bool

Example

>>> some([False, True, 0])
True
>>> some([False, 0, None])
False
>>> some([1, 2, 3, 4], lambda x: x >= 3)
True
>>> some([1, 2, 3, 4], lambda x: x == 0)
False

See also

New in version 1.0.0.

pydash.collections.sort_by(collection, callback=None, reverse=False)[source]

Creates a list of elements, sorted in ascending order by the results of running each element in a collection through the callback.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • callback (mixed, optional) – Callback applied per iteration.
  • reverse (bool, optional) – Whether to reverse the sort. Defaults to False.
Returns:

Sorted list.

Return type:

list

Example

>>> sort_by({'a': 2, 'b': 3, 'c': 1})
[1, 2, 3]
>>> sort_by({'a': 2, 'b': 3, 'c': 1}, reverse=True)
[3, 2, 1]
>>> sort_by([{'a': 2}, {'a': 3}, {'a': 1}], 'a')
[{'a': 1}, {'a': 2}, {'a': 3}]

New in version 1.0.0.

pydash.collections.sort_by_all(collection, keys, orders=None, reverse=False)[source]

This method is like sort_by() except that it sorts by key names instead of an iteratee function. Keys can be sorted in descending order by prepending a "-" to the key name (e.g. "name" would become "-name") or by passing a list of boolean sort options via orders where True is ascending and False is descending.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • keys (list) – List of keys to sort by. By default, keys will be sorted in ascending order. To sort a key in descending order, prepend a "-" to the key name. For example, to sort the key value for "name" in descending order, use "-name".
  • orders (list, optional) – List of boolean sort orders to apply for each key. True corresponds to ascending order while False is descending. Defaults to None.
  • reverse (bool, optional) – Whether to reverse the sort. Defaults to False.
Returns:

Sorted list.

Return type:

list

Example

>>> items = [{'a': 2, 'b': 1}, {'a': 3, 'b': 2}, {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['b', 'a'])
>>> assert results == [{'a': 2, 'b': 1},                               {'a': 3, 'b': 2},                               {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['a', 'b'])
>>> assert results == [{'a': 1, 'b': 3},                               {'a': 2, 'b': 1},                               {'a': 3, 'b': 2}]
>>> results = sort_by_all(items, ['-a', 'b'])
>>> assert results == [{'a': 3, 'b': 2},                               {'a': 2, 'b': 1},                               {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['a', 'b'], [False, True])
>>> assert results == [{'a': 3, 'b': 2},                               {'a': 2, 'b': 1},                               {'a': 1, 'b': 3}]

See also

New in version 3.0.0.

Changed in version 3.2.0: Added orders argument.

Changed in version 3.2.0: Added sort_by_order() as alias.

pydash.collections.sort_by_order(collection, keys, orders=None, reverse=False)

This method is like sort_by() except that it sorts by key names instead of an iteratee function. Keys can be sorted in descending order by prepending a "-" to the key name (e.g. "name" would become "-name") or by passing a list of boolean sort options via orders where True is ascending and False is descending.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • keys (list) – List of keys to sort by. By default, keys will be sorted in ascending order. To sort a key in descending order, prepend a "-" to the key name. For example, to sort the key value for "name" in descending order, use "-name".
  • orders (list, optional) – List of boolean sort orders to apply for each key. True corresponds to ascending order while False is descending. Defaults to None.
  • reverse (bool, optional) – Whether to reverse the sort. Defaults to False.
Returns:

Sorted list.

Return type:

list

Example

>>> items = [{'a': 2, 'b': 1}, {'a': 3, 'b': 2}, {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['b', 'a'])
>>> assert results == [{'a': 2, 'b': 1},                               {'a': 3, 'b': 2},                               {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['a', 'b'])
>>> assert results == [{'a': 1, 'b': 3},                               {'a': 2, 'b': 1},                               {'a': 3, 'b': 2}]
>>> results = sort_by_all(items, ['-a', 'b'])
>>> assert results == [{'a': 3, 'b': 2},                               {'a': 2, 'b': 1},                               {'a': 1, 'b': 3}]
>>> results = sort_by_all(items, ['a', 'b'], [False, True])
>>> assert results == [{'a': 3, 'b': 2},                               {'a': 2, 'b': 1},                               {'a': 1, 'b': 3}]

See also

New in version 3.0.0.

Changed in version 3.2.0: Added orders argument.

Changed in version 3.2.0: Added sort_by_order() as alias.

pydash.collections.to_list(collection)[source]

Converts the collection to a list.

Parameters:collection (list|dict) – Collection to iterate over.
Returns:Collection converted to list.
Return type:list

Example

>>> results = to_list({'a': 1, 'b': 2, 'c': 3})
>>> assert set(results) == set([1, 2, 3])
>>> to_list((1, 2, 3, 4))
[1, 2, 3, 4]

New in version 1.0.0.

pydash.collections.where(collection, properties)[source]

Examines each element in a collection, returning an array of all elements that have the given properties.

Parameters:
  • collection (list|dict) – Collection to iterate over.
  • properties (dict) – property values to filter by
Returns:

filtered list.

Return type:

list

Example

>>> results = where([{'a': 1}, {'b': 2}, {'a': 1, 'b': 3}], {'a': 1})
>>> assert results == [{'a': 1}, {'a': 1, 'b': 3}]

New in version 1.0.0.

Functions

Functions that wrap other functions.

New in version 1.0.0.

pydash.functions.after(func, n)[source]

Creates a function that executes func, with the arguments of the created function, only after being called n times.

Parameters:
  • func (function) – Function to execute.
  • n (int) – Number of times func must be called before it is executed.
Returns:

Function wrapped in an After context.

Return type:

After

Example

>>> func = lambda a, b, c: (a, b, c)
>>> after_func = after(func, 3)
>>> after_func(1, 2, 3)
>>> after_func(1, 2, 3)
>>> after_func(1, 2, 3)
(1, 2, 3)
>>> after_func(4, 5, 6)
(4, 5, 6)

New in version 1.0.0.

Changed in version 3.0.0: Reordered arguments to make func first.

pydash.functions.ary(func, n)[source]

Creates a function that accepts up to n arguments ignoring any additional arguments. Only positional arguments are capped. All keyword arguments are allowed through.

Parameters:
  • func (function) – Function to cap arguments for.
  • n (int) – Number of arguments to accept.
Returns:

Function wrapped in an Ary context.

Return type:

Ary

Example

>>> func = lambda a, b, c=0, d=5: (a, b, c, d)
>>> ary_func = ary(func, 2)
>>> ary_func(1, 2, 3, 4, 5, 6)
(1, 2, 0, 5)
>>> ary_func(1, 2, 3, 4, 5, 6, c=10, d=20)
(1, 2, 10, 20)

New in version 3.0.0.

pydash.functions.before(func, n)[source]

Creates a function that executes func, with the arguments of the created function, until it has been called n times.

Parameters:
  • func (function) – Function to execute.
  • n (int) – Number of times func may be executed.
Returns:

Function wrapped in an Before context.

Return type:

Before

Example

>>> func = lambda a, b, c: (a, b, c)
>>> before_func = before(func, 3)
>>> before_func(1, 2, 3)
(1, 2, 3)
>>> before_func(1, 2, 3)
(1, 2, 3)
>>> before_func(1, 2, 3)
>>> before_func(1, 2, 3)

New in version 1.1.0.

Changed in version 3.0.0: Reordered arguments to make func first.

pydash.functions.compose(*funcs)

This function is like flow() except that it creates a function that invokes the provided functions from right to left. For example, composing the functions f(), g(), and h() produces f(g(h())).

Parameters:*funcs (function) – Function(s) to compose.
Returns:Function(s) wrapped in a Compose context.
Return type:Compose

Example

>>> mult_5 = lambda x: x * 5
>>> div_10 = lambda x: x / 10.0
>>> pow_2 = lambda x: x ** 2
>>> ops = flow_right(mult_5, div_10, pow_2, sum)
>>> ops([1, 2, 3, 4])
50.0

See also

New in version 1.0.0.

Changed in version 2.0.0: Added flow_right() and made compose() an alias.

Changed in version 2.3.1: Added pipe_right() as alias.

pydash.functions.conjoin(*funcs)[source]

Creates a function that composes multiple predicate functions into a single predicate that tests whether all elements of an object pass each predicate.

Parameters:*funcs (function) – Function(s) to conjoin.
Returns:Function(s) wrapped in a Conjoin context.
Return type:Conjoin

Example

>>> conjoiner = conjoin(lambda x: isinstance(x, int), lambda x: x > 3)
>>> conjoiner([1, 2, 3])
False
>>> conjoiner([1.0, 2, 1])
False
>>> conjoiner([4.0, 5, 6])
False
>>> conjoiner([4, 5, 6])
True

New in version 2.0.0.

pydash.functions.curry(func, arity=None)[source]

Creates a function that accepts one or more arguments of func that when invoked either executes func returning its result (if all func arguments have been provided) or returns a function that accepts one or more of the remaining func arguments, and so on.

Parameters:
  • func (function) – Function to curry.
  • arity (int, optional) – Number of function arguments that can be accepted by curried function. Default is to use the number of arguments that are accepted by func.
Returns:

Function wrapped in a Curry context.

Return type:

Curry

Example

>>> func = lambda a, b, c: (a, b, c)
>>> currier = curry(func)
>>> currier = currier(1)
>>> assert isinstance(currier, Curry)
>>> currier = currier(2)
>>> assert isinstance(currier, Curry)
>>> currier = currier(3)
>>> currier
(1, 2, 3)

New in version 1.0.0.

pydash.functions.curry_right(func, arity=None)[source]

This method is like curry() except that arguments are applied to func in the manner of partial_right() instead of partial().

Parameters:
  • func (function) – Function to curry.
  • arity (int, optional) – Number of function arguments that can be accepted by curried function. Default is to use the number of arguments that are accepted by func.
Returns:

Function wrapped in a CurryRight context.

Return type:

CurryRight

Example

>>> func = lambda a, b, c: (a, b, c)
>>> currier = curry_right(func)
>>> currier = currier(1)
>>> assert isinstance(currier, CurryRight)
>>> currier = currier(2)
>>> assert isinstance(currier, CurryRight)
>>> currier = currier(3)
>>> currier
(3, 2, 1)

New in version 1.1.0.

pydash.functions.debounce(func, wait, max_wait=False)[source]

Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked. Subsequent calls to the debounced function will return the result of the last func call.

Parameters:
  • func (function) – Function to execute.
  • wait (int) – Milliseconds to wait before executing func.
  • max_wait (optional) – Maximum time to wait before executing func.
Returns:

Function wrapped in a Debounce context.

Return type:

Debounce

New in version 1.0.0.

pydash.functions.delay(func, wait, *args, **kargs)[source]

Executes the func function after wait milliseconds. Additional arguments will be provided to func when it is invoked.

Parameters:
  • func (function) – Function to execute.
  • wait (int) – Milliseconds to wait before executing func.
  • *args (optional) – Arguments to pass to func.
  • **kargs (optional) – Keyword arguments to pass to func.
Returns:

Return from func.

Return type:

mixed

New in version 1.0.0.

pydash.functions.disjoin(*funcs)[source]

Creates a function that composes multiple predicate functions into a single predicate that tests whether any elements of an object pass each predicate.

Parameters:*funcs (function) – Function(s) to disjoin.
Returns:Function(s) wrapped in a Disjoin context.
Return type:Disjoin

Example

>>> disjoiner = disjoin(lambda x: isinstance(x, float),                                lambda x: isinstance(x, int))
>>> disjoiner([1, '2', '3'])
True
>>> disjoiner([1.0, '2', '3'])
True
>>> disjoiner(['1', '2', '3'])
False

New in version 2.0.0.

pydash.functions.flow(*funcs)[source]

Creates a function that is the composition of the provided functions, where each successive invocation is supplied the return value of the previous. For example, composing the functions f(), g(), and h() produces h(g(f())).

Parameters:*funcs (function) – Function(s) to compose.
Returns:Function(s) wrapped in a Compose context.
Return type:Compose

Example

>>> mult_5 = lambda x: x * 5
>>> div_10 = lambda x: x / 10.0
>>> pow_2 = lambda x: x ** 2
>>> ops = flow(sum, mult_5, div_10, pow_2)
>>> ops([1, 2, 3, 4])
25.0

See also

New in version 2.0.0.

Changed in version 2.3.1: Added pipe() as alias.

pydash.functions.flow_right(*funcs)[source]

This function is like flow() except that it creates a function that invokes the provided functions from right to left. For example, composing the functions f(), g(), and h() produces f(g(h())).

Parameters:*funcs (function) – Function(s) to compose.
Returns:Function(s) wrapped in a Compose context.
Return type:Compose

Example

>>> mult_5 = lambda x: x * 5
>>> div_10 = lambda x: x / 10.0
>>> pow_2 = lambda x: x ** 2
>>> ops = flow_right(mult_5, div_10, pow_2, sum)
>>> ops([1, 2, 3, 4])
50.0

See also

New in version 1.0.0.

Changed in version 2.0.0: Added flow_right() and made compose() an alias.

Changed in version 2.3.1: Added pipe_right() as alias.

pydash.functions.iterated(func)[source]

Creates a function that is composed with itself. Each call to the iterated function uses the previous function call’s result as input. Returned Iterated instance can be called with (initial, n) where initial is the initial value to seed func with and n is the number of times to call func.

Parameters:func (function) – Function to iterate.
Returns:Function wrapped in a Iterated context.
Return type:Iterated

Example

>>> doubler = iterated(lambda x: x * 2)
>>> doubler(4, 5)
128
>>> doubler(3, 9)
1536

New in version 2.0.0.

pydash.functions.juxtapose(*funcs)[source]

Creates a function whose return value is a list of the results of calling each funcs with the supplied arguments.

Parameters:*funcs (function) – Function(s) to juxtapose.
Returns:Function wrapped in a Juxtapose context.
Return type:Juxtapose

Example

>>> double = lambda x: x * 2
>>> triple = lambda x: x * 3
>>> quadruple = lambda x: x * 4
>>> juxtapose(double, triple, quadruple)(5)
[10, 15, 20]

New in version 2.0.0.

pydash.functions.mod_args(func, *transforms)[source]

Creates a function that runs each argument through a corresponding transform function.

Parameters:
  • func (function) – Function to wrap.
  • *transforms (function) – Functions to transform arguments, specified as individual functions or lists of functions.
Returns:

Function wrapped in a ModArgs context.

Return type:

ModArgs

Example

>>> squared = lambda x: x ** 2
>>> double = lambda x: x * 2
>>> modder = mod_args(lambda x, y: [x, y], squared, double)
>>> modder(5, 10)
[25, 20]

New in version 3.3.0.

pydash.functions.negate(func)[source]

Creates a function that negates the result of the predicate func. The func function is executed with the arguments of the created function.

Parameters:func (function) – Function to negate execute.
Returns:Function wrapped in a Negate context.
Return type:Negate

Example

>>> not_is_number = negate(lambda x: isinstance(x, (int, float)))
>>> not_is_number(1)
False
>>> not_is_number('1')
True

New in version 1.1.0.

pydash.functions.once(func)[source]

Creates a function that is restricted to execute func once. Repeat calls to the function will return the value of the first call.

Parameters:func (function) – Function to execute.
Returns:Function wrapped in a Once context.
Return type:Once

Example

>>> oncer = once(lambda *args: args[0])
>>> oncer(5)
5
>>> oncer(6)
5

New in version 1.0.0.

pydash.functions.partial(func, *args, **kargs)[source]

Creates a function that, when called, invokes func with any additional partial arguments prepended to those provided to the new function.

Parameters:
  • func (function) – Function to execute.
  • *args (optional) – Partial arguments to prepend to function call.
  • **kargs (optional) – Partial keyword arguments to bind to function call.
Returns:

Function wrapped in a Partial context.

Return type:

Partial

Example

>>> dropper = partial(lambda array, n: array[n:], [1, 2, 3, 4])
>>> dropper(2)
[3, 4]
>>> dropper(1)
[2, 3, 4]
>>> myrest = partial(lambda array, n: array[n:], n=1)
>>> myrest([1, 2, 3, 4])
[2, 3, 4]

New in version 1.0.0.

pydash.functions.partial_right(func, *args, **kargs)[source]

This method is like partial() except that partial arguments are appended to those provided to the new function.

Parameters:
  • func (function) – Function to execute.
  • *args (optional) – Partial arguments to append to function call.
  • **kargs (optional) – Partial keyword arguments to bind to function call.
Returns:

Function wrapped in a Partial context.

Return type:

Partial

Example

>>> myrest = partial_right(lambda array, n: array[n:], 1)
>>> myrest([1, 2, 3, 4])
[2, 3, 4]

New in version 1.0.0.

pydash.functions.pipe(*funcs)

Creates a function that is the composition of the provided functions, where each successive invocation is supplied the return value of the previous. For example, composing the functions f(), g(), and h() produces h(g(f())).

Parameters:*funcs (function) – Function(s) to compose.
Returns:Function(s) wrapped in a Compose context.
Return type:Compose

Example

>>> mult_5 = lambda x: x * 5
>>> div_10 = lambda x: x / 10.0
>>> pow_2 = lambda x: x ** 2
>>> ops = flow(sum, mult_5, div_10, pow_2)
>>> ops([1, 2, 3, 4])
25.0

See also

New in version 2.0.0.

Changed in version 2.3.1: Added pipe() as alias.

pydash.functions.pipe_right(*funcs)

This function is like flow() except that it creates a function that invokes the provided functions from right to left. For example, composing the functions f(), g(), and h() produces f(g(h())).

Parameters:*funcs (function) – Function(s) to compose.
Returns:Function(s) wrapped in a Compose context.
Return type:Compose

Example

>>> mult_5 = lambda x: x * 5
>>> div_10 = lambda x: x / 10.0
>>> pow_2 = lambda x: x ** 2
>>> ops = flow_right(mult_5, div_10, pow_2, sum)
>>> ops([1, 2, 3, 4])
50.0

See also

New in version 1.0.0.

Changed in version 2.0.0: Added flow_right() and made compose() an alias.

Changed in version 2.3.1: Added pipe_right() as alias.

pydash.functions.rearg(func, *indexes)[source]

Creates a function that invokes func with arguments arranged according to the specified indexes where the argument value at the first index is provided as the first argument, the argument value at the second index is provided as the second argument, and so on.

Parameters:
  • func (function) – Function to rearrange arguments for.
  • *indexes (int) – The arranged argument indexes.
Returns:

Function wrapped in a Rearg context.

Return type:

Rearg

Example

>>> jumble = rearg(lambda *args: args, 1, 2, 3)
>>> jumble(1, 2, 3)
(2, 3, 1)
>>> jumble('a', 'b', 'c', 'd', 'e')
('b', 'c', 'd', 'a', 'e')

New in version 3.0.0.

pydash.functions.spread(func)[source]

Creates a function that invokes func with the array of arguments provided to the created function.

Parameters:func (function) – Function to spread.
Returns:Function wrapped in a Spread context.
Return type:Spread

Example

>>> greet = spread(lambda people: 'Hello ' + ', '.join(people) + '!')
>>> greet(['Mike', 'Don', 'Leo'])
'Hello Mike, Don, Leo!'

New in version 3.1.0.

pydash.functions.throttle(func, wait)[source]

Creates a function that, when executed, will only call the func function at most once per every wait milliseconds. Subsequent calls to the throttled function will return the result of the last func call.

Parameters:
  • func (function) – Function to throttle.
  • wait (int) – Milliseconds to wait before calling func again.
Returns:

Results of last func call.

Return type:

mixed

New in version 1.0.0.

pydash.functions.wrap(value, func)[source]

Creates a function that provides value to the wrapper function as its first argument. Additional arguments provided to the function are appended to those provided to the wrapper function.

Parameters:
  • value (mixed) – Value provided as first argument to function call.
  • func (function) – Function to execute.
Returns:

Function wrapped in a Partial context.

Return type:

Partial

Example

>>> wrapper = wrap('hello', lambda *args: args)
>>> wrapper(1, 2)
('hello', 1, 2)

New in version 1.0.0.

Numerical

Numerical/mathemetical related functions.

New in version 2.1.0.

pydash.numerical.add(collection, callback=None)[source]

Sum each element in collection. If callback is passed, each element of collection is passed through a callback before the summation is computed. If collection and callback are numbers, they are added together.

Parameters:
  • collection (list|dict|number) – Collection to process or first number to add.
  • callback (mixed|number, optional) – Callback applied per iteration or second number to add.
Returns:

Result of summation.

Return type:

number

Example

>>> add([1, 2, 3, 4])
10
>>> add([1, 2, 3, 4], lambda x: x ** 2)
30
>>> add(1, 5)
6

See also

New in version 2.1.0.

Changed in version 3.3.0: Support adding two numbers when passed as positional arguments.

pydash.numerical.average(collection, callback=None)[source]

Calculate arithmetic mean of each element in collection. If callback is passed, each element of collection is passed through a callback before the mean is computed.

Parameters:
  • collection (list|dict) – Collection to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Result of mean.

Return type:

float

Example

>>> average([1, 2, 3, 4])
2.5
>>> average([1, 2, 3, 4], lambda x: x ** 2)
7.5

See also

New in version 2.1.0.

pydash.numerical.avg(collection, callback=None)

Calculate arithmetic mean of each element in collection. If callback is passed, each element of collection is passed through a callback before the mean is computed.

Parameters:
  • collection (list|dict) – Collection to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Result of mean.

Return type:

float

Example

>>> average([1, 2, 3, 4])
2.5
>>> average([1, 2, 3, 4], lambda x: x ** 2)
7.5

See also

New in version 2.1.0.

pydash.numerical.ceil(x, precision=0)[source]

Round number up to precision.

Parameters:
  • x (number) – Number to round up.
  • precision (int, optional) – Rounding precision. Defaults to 0.
Returns:

Number rounded up.

Return type:

int

Example

>>> ceil(3.275) == 4.0
True
>>> ceil(3.215, 1) == 3.3
True
>>> ceil(6.004, 2) == 6.01
True

New in version 3.3.0.

pydash.numerical.curve(x, precision=0)

Round number to precision.

Parameters:
  • x (number) – Number to round.
  • precision (int, optional) – Rounding precision. Defaults to 0.
Returns:

Rounded number.

Return type:

int

Example

>>> round_(3.275) == 3.0
True
>>> round_(3.275, 1) == 3.3
True

See also

New in version 2.1.0.

pydash.numerical.floor(x, precision=0)[source]

Round number down to precision.

Parameters:
  • x (number) – Number to round down.
  • precision (int, optional) – Rounding precision. Defaults to 0.
Returns:

Number rounded down.

Return type:

int

Example

>>> floor(3.75) == 3.0
True
>>> floor(3.215, 1) == 3.2
True
>>> floor(0.046, 2) == 0.04
True

New in version 3.3.0.

pydash.numerical.mean(collection, callback=None)

Calculate arithmetic mean of each element in collection. If callback is passed, each element of collection is passed through a callback before the mean is computed.

Parameters:
  • collection (list|dict) – Collection to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Result of mean.

Return type:

float

Example

>>> average([1, 2, 3, 4])
2.5
>>> average([1, 2, 3, 4], lambda x: x ** 2)
7.5

See also

New in version 2.1.0.

pydash.numerical.median(collection, callback=None)[source]

Calculate median of each element in collection. If callback is passed, each element of collection is passed through a callback before the median is computed.

Parameters:
  • collection (list|dict) – Collection to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Result of median.

Return type:

float

Example

>>> median([1, 2, 3, 4, 5])
3
>>> median([1, 2, 3, 4])
2.5

New in version 2.1.0.

pydash.numerical.moving_average(array, size)[source]

Calculate moving average of each element of array. If callback is passed, each element of array is passed through a callback before the moving average is computed.

Parameters:
  • array (list) – List to process.
  • size (int) – Window size.
Returns:

Result of moving average.

Return type:

list

Example

>>> moving_average(range(10), 1)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
>>> moving_average(range(10), 5)
[2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
>>> moving_average(range(10), 10)
[4.5]

See also

New in version 2.1.0.

pydash.numerical.moving_avg(array, size)

Calculate moving average of each element of array. If callback is passed, each element of array is passed through a callback before the moving average is computed.

Parameters:
  • array (list) – List to process.
  • size (int) – Window size.
Returns:

Result of moving average.

Return type:

list

Example

>>> moving_average(range(10), 1)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
>>> moving_average(range(10), 5)
[2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
>>> moving_average(range(10), 10)
[4.5]

See also

New in version 2.1.0.

pydash.numerical.pow_(x, n)

Calculate exponentiation of x raised to the n power.

Parameters:
  • x (number) – Base number.
  • n (number) – Exponent.
Returns:

Result of calculation.

Return type:

number

Example

>>> power(5, 2)
25
>>> power(12.5, 3)
1953.125

See also

New in version 2.1.0.

pydash.numerical.power(x, n)[source]

Calculate exponentiation of x raised to the n power.

Parameters:
  • x (number) – Base number.
  • n (number) – Exponent.
Returns:

Result of calculation.

Return type:

number

Example

>>> power(5, 2)
25
>>> power(12.5, 3)
1953.125

See also

New in version 2.1.0.

pydash.numerical.round_(x, precision=0)[source]

Round number to precision.

Parameters:
  • x (number) – Number to round.
  • precision (int, optional) – Rounding precision. Defaults to 0.
Returns:

Rounded number.

Return type:

int

Example

>>> round_(3.275) == 3.0
True
>>> round_(3.275, 1) == 3.3
True

See also

New in version 2.1.0.

pydash.numerical.scale(array, maximum=1)[source]

Scale list of value to a maximum number.

Parameters:
  • array (list) – Numbers to scale.
  • maximum (number) – Maximum scale value.
Returns:

Scaled numbers.

Return type:

list

Example

>>> scale([1, 2, 3, 4])
[0.25, 0.5, 0.75, 1.0]
>>> scale([1, 2, 3, 4], 1)
[0.25, 0.5, 0.75, 1.0]
>>> scale([1, 2, 3, 4], 4)
[1.0, 2.0, 3.0, 4.0]
>>> scale([1, 2, 3, 4], 2)
[0.5, 1.0, 1.5, 2.0]

New in version 2.1.0.

pydash.numerical.sigma(array)

Calculate standard deviation of list of numbers.

Parameters:array (list) – List to process.
Returns:Calculated standard deviation.
Return type:float

Example

>>> round(std_deviation([1, 18, 20, 4]), 2) == 8.35
True

See also

New in version 2.1.0.

pydash.numerical.slope(point1, point2)[source]

Calculate the slope between two points.

Parameters:
  • point1 (list|tuple) – X and Y coordinates of first point.
  • point2 (list|tuple) – X and Y cooredinates of second point.
Returns:

Calculated slope.

Return type:

float

Example

>>> slope((1, 2), (4, 8))
2.0

New in version 2.1.0.

pydash.numerical.std_deviation(array)[source]

Calculate standard deviation of list of numbers.

Parameters:array (list) – List to process.
Returns:Calculated standard deviation.
Return type:float

Example

>>> round(std_deviation([1, 18, 20, 4]), 2) == 8.35
True

See also

New in version 2.1.0.

pydash.numerical.sum_(collection, callback=None)

Sum each element in collection. If callback is passed, each element of collection is passed through a callback before the summation is computed. If collection and callback are numbers, they are added together.

Parameters:
  • collection (list|dict|number) – Collection to process or first number to add.
  • callback (mixed|number, optional) – Callback applied per iteration or second number to add.
Returns:

Result of summation.

Return type:

number

Example

>>> add([1, 2, 3, 4])
10
>>> add([1, 2, 3, 4], lambda x: x ** 2)
30
>>> add(1, 5)
6

See also

New in version 2.1.0.

Changed in version 3.3.0: Support adding two numbers when passed as positional arguments.

pydash.numerical.transpose(array)[source]

Transpose the elements of array.

Parameters:array (list) – List to process.
Returns:Transposed list.
Return type:list

Example

>>> transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

New in version 2.1.0.

pydash.numerical.variance(array)[source]

Calculate the variance of the elements in array.

Parameters:array (list) – List to process.
Returns:Calculated variance.
Return type:float

Example

>>> variance([1, 18, 20, 4])
69.6875

New in version 2.1.0.

pydash.numerical.zscore(collection, callback=None)[source]

Calculate the standard score assuming normal distribution. If callback is passed, each element of collection is passed through a callback before the standard score is computed.

Parameters:
  • collection (list|dict) – Collection to process.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Calculated standard score.

Return type:

float

Example

>>> results = zscore([1, 2, 3])

# [-1.224744871391589, 0.0, 1.224744871391589]

New in version 2.1.0.

Objects

Functions that operate on lists, dicts, and other objects.

New in version 1.0.0.

pydash.objects.assign(obj, *sources, **kargs)[source]

Assigns own enumerable properties of source object(s) to the destination object. If callback is supplied, it is invoked with two arguments: (obj_value, source_value).

Parameters:
  • obj (dict) – Destination object whose properties will be modified.
  • sources (dict) – Source objects to assign to obj.
Keyword Arguments:
 

callback (mixed, optional) – Callback applied per iteration.

Returns:

Modified obj.

Return type:

dict

Warning

obj is modified in place.

Example

>>> obj = {}
>>> obj2 = assign(obj, {'a': 1}, {'b': 2}, {'c': 3})
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj is obj2
True

See also

New in version 1.0.0.

Changed in version 2.3.2: Apply clone_deep() to each source before assigning to obj.

Changed in version 3.0.0: Allow callbacks to accept partial arguments.

Changed in version 3.4.4: Shallow copy each source instead of deep copying.

pydash.objects.callables(obj)[source]

Creates a sorted list of keys of an object that are callable.

Parameters:obj (list|dict) – Object to inspect.
Returns:All keys whose values are callable.
Return type:list

Example

>>> callables({'a': 1, 'b': lambda: 2, 'c': lambda: 3})
['b', 'c']

See also

New in version 1.0.0.

Changed in version 2.0.0: Renamed functions to callables.

pydash.objects.clone(value, is_deep=False, callback=None)[source]

Creates a clone of value. If is_deep is True nested valueects will also be cloned, otherwise they will be assigned by reference. If a callback is provided it will be executed to produce the cloned values. The callback is invoked with one argument: (value).

Parameters:
  • value (list|dict) – Object to clone.
  • is_deep (bool, optional) – Whether to perform deep clone.
  • callback (mixed, optional) – Callback applied per iteration.

Example

>>> x = {'a': 1, 'b': 2, 'c': {'d': 3}}
>>> y = clone(x)
>>> y == y
True
>>> x is y
False
>>> x['c'] is y['c']
True
>>> z = clone(x, is_deep=True)
>>> x == z
True
>>> x['c'] is z['c']
False
Returns:Cloned object.
Return type:list|dict

New in version 1.0.0.

pydash.objects.clone_deep(value, callback=None)[source]

Creates a deep clone of value. If a callback is provided it will be executed to produce the cloned values. The callback is invoked with one argument: (value).

Parameters:
  • value (list|dict) – Object to clone.
  • callback (mixed, optional) – Callback applied per iteration.
Returns:

Cloned object.

Return type:

list|dict

Example

>>> x = {'a': 1, 'b': 2, 'c': {'d': 3}}
>>> y = clone_deep(x)
>>> y == y
True
>>> x is y
False
>>> x['c'] is y['c']
False

New in version 1.0.0.

pydash.objects.deep_get(obj, path, default=None)

Get the value at any depth of a nested object based on the path described by path. If path doesn’t exist, default is returned.

Parameters:
  • obj (list|dict) – Object to process.
  • path (str|list) – List or . delimited string of path describing path.
Keyword Arguments:
 

default (mixed) – Default value to return if path doesn’t exist. Defaults to None.

Returns:

Value of obj at path.

Return type:

mixed

Example

>>> get({}, 'a.b.c') is None
True
>>> get({'a': {'b': {'c': [1, 2, 3, 4]}}}, 'a.b.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2') is None
True

See also

New in version 2.0.0.

Changed in version 2.2.0: Support escaping ”.” delimiter in single string path key.

Changed in version 3.4.7: Fixed bug where an iterable default was iterated over instead of being returned when an object path wasn’t found.

pydash.objects.deep_has(obj, path)

Checks if path exists as a key of obj.

Parameters:
  • obj (mixed) – Object to test.
  • path (mixed) – Path to test for. Can be a list of nested keys or a . delimited string of path describing the path.
Returns:

Whether obj has path.

Return type:

bool

Example

>>> has([1, 2, 3], 1)
True
>>> has({'a': 1, 'b': 2}, 'b')
True
>>> has({'a': 1, 'b': 2}, 'c')
False
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
True
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2')
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Return False on ValueError when checking path.

pydash.objects.deep_set(obj, path, value)

Sets the value of an object described by path. If any part of the object path doesn’t exist, it will be created.

Parameters:
  • obj (list|dict) – Object to modify.
  • path (str | list) – Target path to set value to.
  • value (mixed) – Value to set.
Returns:

Modified obj.

Return type:

mixed

Example

>>> set_({}, 'a.b.c', 1)
{'a': {'b': {'c': 1}}}
>>> set_({}, 'a.0.c', 1)
{'a': {'0': {'c': 1}}}
>>> set_([1, 2], '2.0', 1)
[1, 2, [1]]

New in version 2.2.0.

Changed in version 3.3.0: Added set_() as main definition and deep_set() as alias.

pydash.objects.deep_map_values(obj, callback=None, property_path=<pydash.helpers._NoValue object>)[source]

Map all non-object values in obj with return values from callback. The callback is invoked with two arguments: (obj_value, property_path) where property_path contains the list of path keys corresponding to the path of obj_value.

Parameters:
  • obj (list|dict) – Object to map.
  • callback (function) – Callback applied to each value.
Returns:

The modified object.

Return type:

mixed

Warning

obj is modified in place.

Example

>>> x = {'a': 1, 'b': {'c': 2}}
>>> y = deep_map_values(x, lambda val: val * 2)
>>> y == {'a': 2, 'b': {'c': 4}}
True
>>> z = deep_map_values(x, lambda val, props: props)
>>> z == {'a': ['a'], 'b': {'c': ['b', 'c']}}
True

Changed in version 3.0.0: Allow callbacks to accept partial arguments.

pydash.objects.defaults(obj, *sources)[source]

Assigns own enumerable properties of source object(s) to the destination object for all destination properties that resolve to undefined.

Parameters:
  • obj (dict) – Destination object whose properties will be modified.
  • sources (dict) – Source objects to assign to obj.
Returns:

Modified obj.

Return type:

dict

Warning

obj is modified in place.

Example

>>> obj = {'a': 1}
>>> obj2 = defaults(obj, {'b': 2}, {'c': 3}, {'a': 4})
>>> obj is obj2
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True

New in version 1.0.0.

pydash.objects.defaults_deep(obj, *sources)[source]

This method is like defaults() except that it recursively assigns default properties.

Parameters:
  • obj (dict) – Destination object whose properties will be modified.
  • sources (dict) – Source objects to assign to obj.
Returns:

Modified obj.

Return type:

dict

Warning

obj is modified in place.

Example

>>> obj = {'a': {'b': 1}}
>>> obj2 = defaults_deep(obj, {'a': {'b': 2, 'c': 3}})
>>> obj is obj2
True
>>> obj == {'a': {'b': 1, 'c': 3}}
True

New in version 3.3.0.

pydash.objects.extend(obj, *sources, **kargs)

Assigns own enumerable properties of source object(s) to the destination object. If callback is supplied, it is invoked with two arguments: (obj_value, source_value).

Parameters:
  • obj (dict) – Destination object whose properties will be modified.
  • sources (dict) – Source objects to assign to obj.
Keyword Arguments:
 

callback (mixed, optional) – Callback applied per iteration.

Returns:

Modified obj.

Return type:

dict

Warning

obj is modified in place.

Example

>>> obj = {}
>>> obj2 = assign(obj, {'a': 1}, {'b': 2}, {'c': 3})
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj is obj2
True

See also

New in version 1.0.0.

Changed in version 2.3.2: Apply clone_deep() to each source before assigning to obj.

Changed in version 3.0.0: Allow callbacks to accept partial arguments.

Changed in version 3.4.4: Shallow copy each source instead of deep copying.

pydash.objects.find_key(obj, callback=None)[source]

This method is like pydash.arrays.find_index() except that it returns the key of the first element that passes the callback check, instead of the element itself.

Parameters:
  • obj (list|dict) – Object to search.
  • callback (mixed) – Callback applied per iteration.
Returns:

Found key or None.

Return type:

mixed

Example

>>> find_key({'a': 1, 'b': 2, 'c': 3}, lambda x: x == 1)
'a'
>>> find_key([1, 2, 3, 4], lambda x: x == 1)
0

See also

New in version 1.0.0.

pydash.objects.find_last_key(obj, callback=None)

This method is like pydash.arrays.find_index() except that it returns the key of the first element that passes the callback check, instead of the element itself.

Parameters:
  • obj (list|dict) – Object to search.
  • callback (mixed) – Callback applied per iteration.
Returns:

Found key or None.

Return type:

mixed

Example

>>> find_key({'a': 1, 'b': 2, 'c': 3}, lambda x: x == 1)
'a'
>>> find_key([1, 2, 3, 4], lambda x: x == 1)
0

See also

New in version 1.0.0.

pydash.objects.for_in(obj, callback=None)[source]

Iterates over own and inherited enumerable properties of obj, executing callback for each property.

Parameters:
  • obj (list|dict) – Object to process.
  • callback (mixed) – Callback applied per iteration.
Returns:

obj.

Return type:

list|dict

Example

>>> obj = {}
>>> def cb(v, k): obj[k] = v
>>> results = for_in({'a': 1, 'b': 2, 'c': 3}, cb)
>>> results == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True

See also

New in version 1.0.0.

pydash.objects.for_in_right(obj, callback=None)[source]

This function is like for_in() except it iterates over the properties in reverse order.

Parameters:
  • obj (list|dict) – Object to process.
  • callback (mixed) – Callback applied per iteration.
Returns:

obj.

Return type:

list|dict

Example

>>> data = {'product': 1}
>>> def cb(v): data['product'] *= v
>>> for_in_right([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> data['product'] == 24
True

See also

New in version 1.0.0.

pydash.objects.for_own(obj, callback=None)

Iterates over own and inherited enumerable properties of obj, executing callback for each property.

Parameters:
  • obj (list|dict) – Object to process.
  • callback (mixed) – Callback applied per iteration.
Returns:

obj.

Return type:

list|dict

Example

>>> obj = {}
>>> def cb(v, k): obj[k] = v
>>> results = for_in({'a': 1, 'b': 2, 'c': 3}, cb)
>>> results == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True

See also

New in version 1.0.0.

pydash.objects.for_own_right(obj, callback=None)

This function is like for_in() except it iterates over the properties in reverse order.

Parameters:
  • obj (list|dict) – Object to process.
  • callback (mixed) – Callback applied per iteration.
Returns:

obj.

Return type:

list|dict

Example

>>> data = {'product': 1}
>>> def cb(v): data['product'] *= v
>>> for_in_right([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> data['product'] == 24
True

See also

New in version 1.0.0.

pydash.objects.get(obj, path, default=None)[source]

Get the value at any depth of a nested object based on the path described by path. If path doesn’t exist, default is returned.

Parameters:
  • obj (list|dict) – Object to process.
  • path (str|list) – List or . delimited string of path describing path.
Keyword Arguments:
 

default (mixed) – Default value to return if path doesn’t exist. Defaults to None.

Returns:

Value of obj at path.

Return type:

mixed

Example

>>> get({}, 'a.b.c') is None
True
>>> get({'a': {'b': {'c': [1, 2, 3, 4]}}}, 'a.b.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2') is None
True

See also

New in version 2.0.0.

Changed in version 2.2.0: Support escaping ”.” delimiter in single string path key.

Changed in version 3.4.7: Fixed bug where an iterable default was iterated over instead of being returned when an object path wasn’t found.

pydash.objects.get_path(obj, path, default=None)

Get the value at any depth of a nested object based on the path described by path. If path doesn’t exist, default is returned.

Parameters:
  • obj (list|dict) – Object to process.
  • path (str|list) – List or . delimited string of path describing path.
Keyword Arguments:
 

default (mixed) – Default value to return if path doesn’t exist. Defaults to None.

Returns:

Value of obj at path.

Return type:

mixed

Example

>>> get({}, 'a.b.c') is None
True
>>> get({'a': {'b': {'c': [1, 2, 3, 4]}}}, 'a.b.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2') is None
True

See also

New in version 2.0.0.

Changed in version 2.2.0: Support escaping ”.” delimiter in single string path key.

Changed in version 3.4.7: Fixed bug where an iterable default was iterated over instead of being returned when an object path wasn’t found.

pydash.objects.has(obj, path)[source]

Checks if path exists as a key of obj.

Parameters:
  • obj (mixed) – Object to test.
  • path (mixed) – Path to test for. Can be a list of nested keys or a . delimited string of path describing the path.
Returns:

Whether obj has path.

Return type:

bool

Example

>>> has([1, 2, 3], 1)
True
>>> has({'a': 1, 'b': 2}, 'b')
True
>>> has({'a': 1, 'b': 2}, 'c')
False
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
True
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2')
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Return False on ValueError when checking path.

pydash.objects.has_path(obj, path)

Checks if path exists as a key of obj.

Parameters:
  • obj (mixed) – Object to test.
  • path (mixed) – Path to test for. Can be a list of nested keys or a . delimited string of path describing the path.
Returns:

Whether obj has path.

Return type:

bool

Example

>>> has([1, 2, 3], 1)
True
>>> has({'a': 1, 'b': 2}, 'b')
True
>>> has({'a': 1, 'b': 2}, 'c')
False
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
True
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2')
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Return False on ValueError when checking path.

pydash.objects.invert(obj, multivalue=False)[source]

Creates an object composed of the inverted keys and values of the given object.

Parameters:
  • obj (dict) – Dict to invert.
  • multivalue (bool, optional) – Whether to return inverted values as lists. Defaults to False.
Returns:

Inverted dict.

Return type:

dict

Example

>>> results = invert({'a': 1, 'b': 2, 'c': 3})
>>> results == {1: 'a', 2: 'b', 3: 'c'}
True
>>> results = invert({'a': 1, 'b': 2, 'c': 1}, multivalue=True)
>>> set(results[1]) == set(['a', 'c'])
True

Note

Assumes dict values are hashable as dict keys.

New in version 1.0.0.

Changed in version 2.0.0: Added multivalue argument.

pydash.objects.keys(obj)[source]

Creates a list composed of the keys of obj.

Parameters:obj (mixed) – Object to extract keys from.
Returns:List of keys.
Return type:list

Example

>>> keys([1, 2, 3])
[0, 1, 2]
>>> set(keys({'a': 1, 'b': 2, 'c': 3})) == set(['a', 'b', 'c'])
True

See also

New in version 1.0.0.

Changed in version 1.1.0: Added keys_in() as alias.

pydash.objects.keys_in(obj)

Creates a list composed of the keys of obj.

Parameters:obj (mixed) – Object to extract keys from.
Returns:List of keys.
Return type:list

Example

>>> keys([1, 2, 3])
[0, 1, 2]
>>> set(keys({'a': 1, 'b': 2, 'c': 3})) == set(['a', 'b', 'c'])
True

See also

New in version 1.0.0.

Changed in version 1.1.0: Added keys_in() as alias.

pydash.objects.map_keys(obj, callback=None)[source]

Creates an object with the same values as obj and keys generated by running each property of obj through the callback. The callback is invoked with three arguments: (value, key, object). If a property name is provided for callback the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is provided for callback the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • obj (list|dict) – Object to map.
  • callback (mixed) – Callback applied per iteration.
Returns:

Results of running obj through callback.

Return type:

list|dict

Example

>>> callback = lambda value, key: key * 2
>>> results = map_keys({'a': 1, 'b': 2, 'c': 3}, callback)
>>> results == {'aa': 1, 'bb': 2, 'cc': 3}
True

New in version 3.3.0.

pydash.objects.map_values(obj, callback=None)[source]

Creates an object with the same keys as obj and values generated by running each property of obj through the callback. The callback is invoked with three arguments: (value, key, object). If a property name is provided for callback the created pydash.collections.pluck() style callback will return the property value of the given element. If an object is provided for callback the created pydash.collections.where() style callback will return True for elements that have the properties of the given object, else False.

Parameters:
  • obj (list|dict) – Object to map.
  • callback (mixed) – Callback applied per iteration.
Returns:

Results of running obj through callback.

Return type:

list|dict

Example

>>> results = map_values({'a': 1, 'b': 2, 'c': 3}, lambda x: x * 2)
>>> results == {'a': 2, 'b': 4, 'c': 6}
True
>>> results = map_values({'a': 1, 'b': {'d': 4}, 'c': 3}, {'d': 4})
>>> results == {'a': False, 'b': True, 'c': False}
True

New in version 1.0.0.

pydash.objects.merge(obj, *sources, **kargs)[source]

Recursively merges own enumerable properties of the source object(s) that don’t resolve to undefined into the destination object. Subsequent sources will overwrite property assignments of previous sources. If a callback is provided it will be executed to produce the merged values of the destination and source properties. The callback is invoked with at least two arguments: (obj_value, *source_value).

Parameters:
  • obj (dict) – Destination object to merge source(s) into.
  • sources (dict) – Source objects to merge from. subsequent sources overwrite previous ones.
Keyword Arguments:
 

callback (function, optional) – Callback function to handle merging (must be passed in as keyword argument).

Returns:

Merged object.

Return type:

dict

Warning

obj is modified in place.

Example

>>> obj = {'a': 2}
>>> obj2 = merge(obj, {'a': 1}, {'b': 2, 'c': 3}, {'d': 4})
>>> obj2 == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
True
>>> obj is obj2
True

New in version 1.0.0.

Changed in version 2.3.2: Apply clone_deep() to each source before assigning to obj.

Changed in version 2.3.2: Allow callback to be passed by reference if it is the last positional argument.

Changed in version 3.3.0: Added internal option for overriding the default setter for obj values.

pydash.objects.methods(obj)

Creates a sorted list of keys of an object that are callable.

Parameters:obj (list|dict) – Object to inspect.
Returns:All keys whose values are callable.
Return type:list

Example

>>> callables({'a': 1, 'b': lambda: 2, 'c': lambda: 3})
['b', 'c']

See also

New in version 1.0.0.

Changed in version 2.0.0: Renamed functions to callables.

pydash.objects.omit(obj, callback=None, *properties)[source]

Creates a shallow clone of object excluding the specified properties. Property names may be specified as individual arguments or as lists of property names. If a callback is provided it will be executed for each property of object omitting the properties the callback returns truthy for. The callback is invoked with three arguments: (value, key, object).

Parameters:
  • obj (mixed) – Object to process.
  • properties (str) – Property values to omit.
  • callback (mixed, optional) – Callback used to determine whic properties to omit.
Returns:

Results of omitting properties.

Return type:

dict

Example

>>> omit({'a': 1, 'b': 2, 'c': 3}, 'b', 'c') == {'a': 1}
True
>>> omit([1, 2, 3, 4], 0, 3) == {1: 2, 2: 3}
True

New in version 1.0.0.

pydash.objects.pairs(obj)[source]

Creates a two dimensional list of an object’s key-value pairs, i.e. [[key1, value1], [key2, value2]].

Parameters:obj (mixed) – Object to process.
Returns:Two dimensional list of object’s key-value pairs.
Return type:list

Example

>>> pairs([1, 2, 3, 4])
[[0, 1], [1, 2], [2, 3], [3, 4]]
>>> pairs({'a': 1})
[['a', 1]]

New in version 1.0.0.

pydash.objects.parse_int(value, radix=None)[source]

Converts the given value into an integer of the specified radix. If radix is falsey, a radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used.

Parameters:
  • value (mixed) – Value to parse.
  • radix (int, optional) – Base to convert to.
Returns:

Integer if parsable else None.

Return type:

mixed

Example

>>> parse_int('5')
5
>>> parse_int('12', 8)
10
>>> parse_int('x') is None
True

New in version 1.0.0.

pydash.objects.pick(obj, callback=None, *properties)[source]

Creates a shallow clone of object composed of the specified properties. Property names may be specified as individual arguments or as lists of property names. If a callback is provided it will be executed for each property of object picking the properties the callback returns truthy for. The callback is invoked with three arguments: (value, key, object).

Parameters:
  • obj (list|dict) – Object to pick from.
  • properties (str) – Property values to pick.
  • callback (mixed, optional) – Callback used to determine which properties to pick.
Returns:

Dict containg picked properties.

Return type:

dict

Example

>>> pick({'a': 1, 'b': 2, 'c': 3}, 'a', 'b') == {'a': 1, 'b': 2}
True

New in version 1.0.0.

pydash.objects.rename_keys(obj, key_map)[source]

Rename the keys of obj using key_map and return new object.

Parameters:
  • obj (dict) – Object to rename.
  • key_map (dict) – Renaming map whose keys correspond to existing keys in obj and whose values are the new key name.
Returns:

Renamed obj.

Return type:

dict

Example

>>> obj = rename_keys({'a': 1, 'b': 2, 'c': 3}, {'a': 'A', 'b': 'B'})
>>> obj == {'A': 1, 'B': 2, 'c': 3}
True

New in version 2.0.0.

pydash.objects.set_(obj, path, value)[source]

Sets the value of an object described by path. If any part of the object path doesn’t exist, it will be created.

Parameters:
  • obj (list|dict) – Object to modify.
  • path (str | list) – Target path to set value to.
  • value (mixed) – Value to set.
Returns:

Modified obj.

Return type:

mixed

Example

>>> set_({}, 'a.b.c', 1)
{'a': {'b': {'c': 1}}}
>>> set_({}, 'a.0.c', 1)
{'a': {'0': {'c': 1}}}
>>> set_([1, 2], '2.0', 1)
[1, 2, [1]]

New in version 2.2.0.

Changed in version 3.3.0: Added set_() as main definition and deep_set() as alias.

pydash.objects.set_path(obj, value, keys, default=None)[source]

Sets the value of an object described by keys. If any part of the object path doesn’t exist, it will be created with default.

Parameters:
  • obj (list|dict) – Object to modify.
  • value (mixed) – Value to set.
  • keys (list) – Target path to set value to.
  • default (callable, optional) – Callable that returns default value to assign if path part is not set. Defaults to {} if obj is a dict or [] if obj is a list.
Returns:

Modified obj.

Return type:

mixed

Example

>>> set_path({}, 1, ['a', 0], default=[])
{'a': [1]}
>>> set_path({}, 1, ['a', 'b']) == {'a': {'b': 1}}
True

New in version 2.0.0.

pydash.objects.to_boolean(obj, true_values=('true', '1'), false_values=('false', '0'))[source]

Convert obj to boolean. This is not like the builtin bool function. By default commonly considered strings values are converted to their boolean equivalent, i.e., '0' and 'false' are converted to False while '1' and 'true' are converted to True. If a string value is provided that isn’t recognized as having a common boolean conversion, then the returned value is None. Non-string values of obj are converted using bool. Optionally, true_values and false_values can be overridden but each value must be a string.

Parameters:
  • obj (mixed) – Object to convert.
  • true_values (tuple, optional) – Values to consider True. Each value must be a string. Comparision is case-insensitive. Defaults to ('true', '1').
  • false_values (tuple, optional) – Values to consider False. Each value must be a string. Comparision is case-insensitive. Defaults to ('false', '0').
Returns:

Boolean value of obj.

Return type:

bool

Example

>>> to_boolean('true')
True
>>> to_boolean('1')
True
>>> to_boolean('false')
False
>>> to_boolean('0')
False
>>> assert to_boolean('a') is None

New in version 3.0.0.

pydash.objects.to_dict(obj)[source]

Convert obj to dict by created a new dict using obj keys and values.

Parameters:obj – (mixed): Object to convert.
Returns:Object converted to dict.
Return type:dict

Example

>>> obj = {'a': 1, 'b': 2}
>>> obj2 = to_dict(obj)
>>> obj2 == obj
True
>>> obj2 is not obj
True

New in version 3.0.0.

pydash.objects.to_number(obj, precision=0)[source]

Convert obj to a number. All numbers are retuned as float. If precision is negative, round obj to the nearest positive integer place. If obj can’t be converted to a number, None is returned.

Parameters:
  • obj (str|int|float) – Object to convert.
  • precision (int, optional) – Precision to round number to. Defaults to 0.
Returns:

Converted number or None if can’t be converted.

Return type:

float

Example

>>> to_number('1234.5678')
1235.0
>>> to_number('1234.5678', 4)
1234.5678
>>> to_number(1, 2)
1.0

New in version 3.0.0.

pydash.objects.to_plain_object(obj)

Convert obj to dict by created a new dict using obj keys and values.

Parameters:obj – (mixed): Object to convert.
Returns:Object converted to dict.
Return type:dict

Example

>>> obj = {'a': 1, 'b': 2}
>>> obj2 = to_dict(obj)
>>> obj2 == obj
True
>>> obj2 is not obj
True

New in version 3.0.0.

pydash.objects.to_string(obj)[source]

Converts an object to string.

Parameters:obj (mixed) – Object to convert.
Returns:String representation of obj.
Return type:str

Example

>>> to_string(1) == '1'
True
>>> to_string(None) == ''
True
>>> to_string([1, 2, 3]) == '[1, 2, 3]'
True
>>> to_string('a') == 'a'
True

New in version 2.0.0.

Changed in version 3.0.0: Convert None to empty string.

pydash.objects.transform(obj, callback=None, accumulator=None)[source]

An alernative to pydash.collections.reduce(), this method transforms obj to a new accumulator object which is the result of running each of its properties through a callback, with each callback execution potentially mutating the accumulator object. The callback is invoked with four arguments: (accumulator, value, key, object). Callbacks may exit iteration early by explicitly returning False.

Parameters:
  • obj (list|dict) – Object to process.
  • callback (mixed) – Callback applied per iteration.
  • accumulator (mixed, optional) – Accumulated object. Defaults to list.
Returns:

Accumulated object.

Return type:

mixed

Example

>>> transform([1, 2, 3, 4],                      lambda acc, value, key: acc.append((key, value)))
[(0, 1), (1, 2), (2, 3), (3, 4)]

New in version 1.0.0.

pydash.objects.update_path(obj, callback, keys, default=None)[source]

Update the value of an object described by keys using callback. If any part of the object path doesn’t exist, it will be created with default. The callback is invoked with the last key value of obj: (value)

Parameters:
  • obj (list|dict) – Object to modify.
  • callback (function) – Function that returns updated value.
  • keys (list) – A list of string keys that describe the object path to modify.
  • default (mixed, optional) – Default value to assign if path part is not set. Defaults to {} if obj is a dict or [] if obj is a list.
Returns:

Updated obj.

Return type:

mixed

Example

>>> update_path({}, lambda value: value, ['a', 'b'])
{'a': {'b': None}}
>>> update_path([], lambda value: value, [0, 0])
[[None]]

New in version 2.0.0.

pydash.objects.values(obj)[source]

Creates a list composed of the values of obj.

Parameters:obj (mixed) – Object to extract values from.
Returns:List of values.
Return type:list

Example

>>> results = values({'a': 1, 'b': 2, 'c': 3})
>>> set(results) == set([1, 2, 3])
True
>>> values([2, 4, 6, 8])
[2, 4, 6, 8]

See also

New in version 1.0.0.

Changed in version 1.1.0: Added values_in() as alias.

pydash.objects.values_in(obj)

Creates a list composed of the values of obj.

Parameters:obj (mixed) – Object to extract values from.
Returns:List of values.
Return type:list

Example

>>> results = values({'a': 1, 'b': 2, 'c': 3})
>>> set(results) == set([1, 2, 3])
True
>>> values([2, 4, 6, 8])
[2, 4, 6, 8]

See also

New in version 1.0.0.

Changed in version 1.1.0: Added values_in() as alias.

Predicates

Predicate functions that return boolean evaluations of objects.

New in version 2.0.0.

pydash.predicates.gt(value, other)[source]

Checks if value is greater than other.

Parameters:
  • value (number) – Value to compare.
  • other (number) – Other value to compare.
Returns:

Whether value is greater than other.

Return type:

bool

Example

>>> gt(5, 3)
True
>>> gt(3, 5)
False
>>> gt(5, 5)
False

New in version 3.3.0.

pydash.predicates.gte(value, other)[source]

Checks if value is greater than or equal to other.

Parameters:
  • value (number) – Value to compare.
  • other (number) – Other value to compare.
Returns:

Whether value is greater than or equal to other.

Return type:

bool

Example

>>> gte(5, 3)
True
>>> gte(3, 5)
False
>>> gte(5, 5)
True

New in version 3.3.0.

pydash.predicates.lt(value, other)[source]

Checks if value is less than other.

Parameters:
  • value (number) – Value to compare.
  • other (number) – Other value to compare.
Returns:

Whether value is less than other.

Return type:

bool

Example

>>> lt(5, 3)
False
>>> lt(3, 5)
True
>>> lt(5, 5)
False

New in version 3.3.0.

pydash.predicates.lte(value, other)[source]

Checks if value is less than or equal to other.

Parameters:
  • value (number) – Value to compare.
  • other (number) – Other value to compare.
Returns:

Whether value is less than or equal to other.

Return type:

bool

Example

>>> lte(5, 3)
False
>>> lte(3, 5)
True
>>> lte(5, 5)
True

New in version 3.3.0.

pydash.predicates.in_range(value, start=0, end=None)[source]

Checks if value is between start and up to but not including end. If end is not specified it defaults to start with start becoming 0.

Parameters:
  • value (int|float) – Number to check.
  • start (int|float, optional) – Start of range inclusive. Defaults to 0.
  • end (int|float, optional) – End of range exclusive. Defaults to start.
Returns:

Whether value is in range.

Return type:

bool

Example

>>> in_range(2, 4)
True
>>> in_range(4, 2)
False
>>> in_range(2, 1, 3)
True
>>> in_range(3, 1, 2)
False
>>> in_range(2.5, 3.5)
True
>>> in_range(3.5, 2.5)
False

New in version 3.1.0.

pydash.predicates.is_associative(value)[source]

Checks if value is an associative object meaning that it can be accessed via an index or key

Parameters:value (mixed) – Value to check.
Returns:Whether value is associative.
Return type:bool

Example

>>> is_associative([])
True
>>> is_associative({})
True
>>> is_associative(1)
False
>>> is_associative(True)
False

New in version 2.0.0.

pydash.predicates.is_blank(text)[source]

Checks if text contains only whitespace characters.

Parameters:text (str) – String to test.
Returns:Whether text is blank.
Return type:bool

Example

>>> is_blank('')
True
>>> is_blank(' \r\n ')
True
>>> is_blank(False)
False

New in version 3.0.0.

pydash.predicates.is_boolean(value)[source]

Checks if value is a boolean value.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a boolean.
Return type:bool

Example

>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(0)
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_bool as alias.

pydash.predicates.is_bool(value)

Checks if value is a boolean value.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a boolean.
Return type:bool

Example

>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(0)
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_bool as alias.

pydash.predicates.is_builtin(value)[source]

Checks if value is a Python builtin function or method.

Parameters:value (function) – Value to check.
Returns:Whether value is a Python builtin function or method.
Return type:bool

Example

>>> is_builtin(1)
True
>>> is_builtin(list)
True
>>> is_builtin('foo')
False

See also

New in version 3.0.0.

pydash.predicates.is_date(value)[source]

Check if value is a date object.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a date object.
Return type:bool

Example

>>> import datetime
>>> is_date(datetime.date.today())
True
>>> is_date(datetime.datetime.today())
True
>>> is_date('2014-01-01')
False

Note

This will also return True for datetime objects.

New in version 1.0.0.

pydash.predicates.is_decreasing(value)[source]

Check if value is monotonically decreasing.

Parameters:value (list) – Value to check.
Returns:Whether value is monotonically decreasing.
Return type:bool

Example

>>> is_decreasing([5, 4, 4, 3])
True
>>> is_decreasing([5, 5, 5])
True
>>> is_decreasing([5, 4, 5])
False

New in version 2.0.0.

pydash.predicates.is_dict(value)[source]

Checks if value is a dict.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a dict.
Return type:bool

Example

>>> is_dict({})
True
>>> is_dict([])
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_dict() as main definition and made is_plain_object() an alias.

pydash.predicates.is_empty(value)[source]

Checks if value is empty.

Parameters:value (mixed) – Value to check.
Returns:Whether value is empty.
Return type:bool

Example

>>> is_empty(0)
True
>>> is_empty(1)
True
>>> is_empty(True)
True
>>> is_empty('foo')
False
>>> is_empty(None)
True
>>> is_empty({})
True

Note

Returns True for booleans and numbers.

New in version 1.0.0.

pydash.predicates.is_equal(value, other, callback=None)[source]

Performs a comparison between two values to determine if they are equivalent to each other. If a callback is provided it will be executed to compare values. If the callback returns None, comparisons will be handled by the method instead. The callback is invoked with two arguments: (value, other).

Parameters:
  • value (list|dict) – Object to compare.
  • other (list|dict) – Object to compare.
  • callback (mixed, optional) – Callback used to compare values from value and other.
Returns:

Whether value and other are equal.

Return type:

bool

Example

>>> is_equal([1, 2, 3], [1, 2, 3])
True
>>> is_equal('a', 'A')
False
>>> is_equal('a', 'A', lambda a, b: a.lower() == b.lower())
True

New in version 1.0.0.

pydash.predicates.is_error(value)[source]

Checks if value is an Exception.

Parameters:value (mixed) – Value to check.
Returns:Whether value is an exception.
Return type:bool

Example

>>> is_error(Exception())
True
>>> is_error(Exception)
False
>>> is_error(None)
False

New in version 1.1.0.

pydash.predicates.is_even(value)[source]

Checks if value is even.

Parameters:value (mixed) – Value to check.
Returns:Whether value is even.
Return type:bool

Example

>>> is_even(2)
True
>>> is_even(3)
False
>>> is_even(False)
False

New in version 2.0.0.

pydash.predicates.is_float(value)[source]

Checks if value is a float.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a float.
Return type:bool

Example

>>> is_float(1.0)
True
>>> is_float(1)
False

New in version 2.0.0.

pydash.predicates.is_function(value)[source]

Checks if value is a function.

Parameters:value (mixed) – Value to check.
Returns:Whether value is callable.
Return type:bool

Example

>>> is_function(list)
True
>>> is_function(lambda: True)
True
>>> is_function(1)
False

New in version 1.0.0.

pydash.predicates.is_increasing(value)[source]

Check if value is monotonically increasing.

Parameters:value (list) – Value to check.
Returns:Whether value is monotonically increasing.
Return type:bool

Example

>>> is_increasing([1, 3, 5])
True
>>> is_increasing([1, 1, 2, 3, 3])
True
>>> is_increasing([5, 5, 5])
True
>>> is_increasing([1, 2, 4, 3])
False

New in version 2.0.0.

pydash.predicates.is_indexed(value)[source]

Checks if value is integer indexed, i.e., list, str or tuple.

Parameters:value (mixed) – Value to check.
Returns:Whether value is integer indexed.
Return type:bool

Example

>>> is_indexed('')
True
>>> is_indexed([])
True
>>> is_indexed(())
True
>>> is_indexed({})
False

New in version 2.0.0.

Changed in version 3.0.0: Return True for tuples.

pydash.predicates.is_instance_of(value, types)[source]

Checks if value is an instance of types.

Parameters:
  • value (mixed) – Value to check.
  • types (mixed) – Types to check against. Pass as tuple to check if value is one of multiple types.
Returns:

Whether value is an instance of types.

Return type:

bool

Example

>>> is_instance_of({}, dict)
True
>>> is_instance_of({}, list)
False

New in version 2.0.0.

pydash.predicates.is_integer(value)[source]

Checks if value is a integer.

Parameters:value (mixed) – Value to check.
Returns:Whether value is an integer.
Return type:bool

Example

>>> is_integer(1)
True
>>> is_integer(1.0)
False
>>> is_integer(True)
False

See also

New in version 2.0.0.

Changed in version 3.0.0: Added is_int as alias.

pydash.predicates.is_int(value)

Checks if value is a integer.

Parameters:value (mixed) – Value to check.
Returns:Whether value is an integer.
Return type:bool

Example

>>> is_integer(1)
True
>>> is_integer(1.0)
False
>>> is_integer(True)
False

See also

New in version 2.0.0.

Changed in version 3.0.0: Added is_int as alias.

pydash.predicates.is_iterable(value)[source]

Checks if value is an iterable.

Parameters:value (mixed) – Value to check.
Returns:Whether value is an iterable.
Return type:bool

Example

>>> is_iterable([])
True
>>> is_iterable({})
True
>>> is_iterable(())
True
>>> is_iterable(5)
False
>>> is_iterable(True)
False

New in version 3.3.0.

pydash.predicates.is_json(value)[source]

Checks if value is a valid JSON string.

Parameters:value (mixed) – Value to check.
Returns:Whether value is JSON.
Return type:bool

Example

>>> is_json({})
False
>>> is_json('{}')
True
>>> is_json({"hello": 1, "world": 2})
False
>>> is_json('{"hello": 1, "world": 2}')
True

New in version 2.0.0.

pydash.predicates.is_list(value)[source]

Checks if value is a list.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a list.
Return type:bool

Example

>>> is_list([])
True
>>> is_list({})
False
>>> is_list(())
False

New in version 1.0.0.

pydash.predicates.is_match(obj, source, callback=None)[source]

Performs a comparison between obj and source to determine if obj contains equivalent property values as source. If a callback is provided it will be executed to compare values. If the callback returns None, comparisons will be handled by the method instead. The callback is invoked with two arguments: (obj, source).

Parameters:
  • obj (list|dict) – Object to compare.
  • source (list|dict) – Object of property values to match.
  • callback (mixed, optional) – Callback used to compare values from obj and source.
Returns:

Whether obj is a match or not.

Return type:

bool

Example

>>> is_match({'a': 1, 'b': 2}, {'b': 2})
True
>>> is_match({'a': 1, 'b': 2}, {'b': 3})
False
>>> is_match({'a': [{'b': [{'c': 3, 'd': 4}]}]},                     {'a': [{'b': [{'d': 4}]}]})
True

New in version 3.0.0.

Changed in version 3.2.0: Don’t compare obj and source using type. Use isinstance exclusively.

pydash.predicates.is_monotone(value, op)[source]

Checks if value is monotonic when operator used for comparison.

Parameters:
  • value (list) – Value to check.
  • op (function) – Operation to used for comparison.
Returns:

Whether value is monotone.

Return type:

bool

Example

>>> is_monotone([1, 1, 2, 3], operator.le)
True
>>> is_monotone([1, 1, 2, 3], operator.lt)
False

New in version 2.0.0.

pydash.predicates.is_nan(value)[source]

Checks if value is not a number.

Parameters:value (mixed) – Value to check.
Returns:Whether value is not a number.
Return type:bool

Example

>>> is_nan('a')
True
>>> is_nan(1)
False
>>> is_nan(1.0)
False

New in version 1.0.0.

pydash.predicates.is_native(value)

Checks if value is a Python builtin function or method.

Parameters:value (function) – Value to check.
Returns:Whether value is a Python builtin function or method.
Return type:bool

Example

>>> is_builtin(1)
True
>>> is_builtin(list)
True
>>> is_builtin('foo')
False

See also

New in version 3.0.0.

pydash.predicates.is_negative(value)[source]

Checks if value is negative.

Parameters:value (mixed) – Value to check.
Returns:Whether value is negative.
Return type:bool

Example

>>> is_negative(-1)
True
>>> is_negative(0)
False
>>> is_negative(1)
False

New in version 2.0.0.

pydash.predicates.is_none(value)[source]

Checks if value is None.

Parameters:value (mixed) – Value to check.
Returns:Whether value is None.
Return type:bool

Example

>>> is_none(None)
True
>>> is_none(False)
False

New in version 1.0.0.

pydash.predicates.is_number(value)[source]

Checks if value is a number.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a number.
Return type:bool

Note

Returns True for int, long (PY2), float, and decimal.Decimal.

Example

>>> is_number(1)
True
>>> is_number(1.0)
True
>>> is_number('a')
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_num as alias.

pydash.predicates.is_num(value)

Checks if value is a number.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a number.
Return type:bool

Note

Returns True for int, long (PY2), float, and decimal.Decimal.

Example

>>> is_number(1)
True
>>> is_number(1.0)
True
>>> is_number('a')
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_num as alias.

pydash.predicates.is_object(value)[source]

Checks if value is a list or dict.

Parameters:value (mixed) – Value to check.
Returns:Whether value is list or dict.
Return type:bool

Example

>>> is_object([])
True
>>> is_object({})
True
>>> is_object(())
False
>>> is_object(1)
False

New in version 1.0.0.

pydash.predicates.is_odd(value)[source]

Checks if value is odd.

Parameters:value (mixed) – Value to check.
Returns:Whether value is odd.
Return type:bool

Example

>>> is_odd(3)
True
>>> is_odd(2)
False
>>> is_odd('a')
False

New in version 2.0.0.

pydash.predicates.is_plain_object(value)

Checks if value is a dict.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a dict.
Return type:bool

Example

>>> is_dict({})
True
>>> is_dict([])
False

See also

New in version 1.0.0.

Changed in version 3.0.0: Added is_dict() as main definition and made is_plain_object() an alias.

pydash.predicates.is_positive(value)[source]

Checks if value is positive.

Parameters:value (mixed) – Value to check.
Returns:Whether value is positive.
Return type:bool

Example

>>> is_positive(1)
True
>>> is_positive(0)
False
>>> is_positive(-1)
False

New in version 2.0.0.

pydash.predicates.is_re(value)

Checks if value is a RegExp object.

Parameters:value (mxied) – Value to check.
Returns:Whether value is a RegExp object.
Return type:bool

Example

>>> is_reg_exp(re.compile(''))
True
>>> is_reg_exp('')
False

See also

New in version 1.1.0.

pydash.predicates.is_reg_exp(value)[source]

Checks if value is a RegExp object.

Parameters:value (mxied) – Value to check.
Returns:Whether value is a RegExp object.
Return type:bool

Example

>>> is_reg_exp(re.compile(''))
True
>>> is_reg_exp('')
False

See also

New in version 1.1.0.

pydash.predicates.is_strictly_decreasing(value)[source]

Check if value is strictly decreasing.

Parameters:value (list) – Value to check.
Returns:Whether value is strictly decreasing.
Return type:bool

Example

>>> is_strictly_decreasing([4, 3, 2, 1])
True
>>> is_strictly_decreasing([4, 4, 2, 1])
False

New in version 2.0.0.

pydash.predicates.is_strictly_increasing(value)[source]

Check if value is strictly increasing.

Parameters:value (list) – Value to check.
Returns:Whether value is strictly increasing.
Return type:bool

Example

>>> is_strictly_increasing([1, 2, 3, 4])
True
>>> is_strictly_increasing([1, 1, 3, 4])
False

New in version 2.0.0.

pydash.predicates.is_string(value)[source]

Checks if value is a string.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a string.
Return type:bool

Example

>>> is_string('')
True
>>> is_string(1)
False

New in version 1.0.0.

pydash.predicates.is_tuple(value)[source]

Checks if value is a tuple.

Parameters:value (mixed) – Value to check.
Returns:Whether value is a tuple.
Return type:bool

Example

>>> is_tuple(())
True
>>> is_tuple({})
False
>>> is_tuple([])
False

New in version 3.0.0.

pydash.predicates.is_zero(value)[source]

Checks if value is 0.

Parameters:value (mixed) – Value to check.
Returns:Whether value is 0.
Return type:bool

Example

>>> is_zero(0)
True
>>> is_zero(1)
False

New in version 2.0.0.

Strings

String functions.

New in version 1.1.0.

pydash.strings.camel_case(text)[source]

Converts text to camel case.

Parameters:text (str) – String to convert.
Returns:String converted to camel case.
Return type:str

Example

>>> camel_case('FOO BAR_bAz')
'fooBarBAz'

New in version 1.1.0.

pydash.strings.capitalize(text, strict=True)[source]

Capitalizes the first character of text.

Parameters:
  • text (str) – String to capitalize.
  • strict (bool, optional) – Whether to cast rest of string to lower case. Defaults to True.
Returns:

Capitalized string.

Return type:

str

Example

>>> capitalize('once upon a TIME')
'Once upon a time'
>>> capitalize('once upon a TIME', False)
'Once upon a TIME'

New in version 1.1.0.

Changed in version 3.0.0: Added strict option.

pydash.strings.chop(text, step)[source]

Break up text into intervals of length step.

Parameters:
  • text (str) – String to chop.
  • step (int) – Interval to chop text.
Returns:

List of chopped characters. If text is None an empty list is returned.

Return type:

list

Example

>>> chop('abcdefg', 3)
['abc', 'def', 'g']

New in version 3.0.0.

pydash.strings.chop_right(text, step)[source]

Like chop() except text is chopped from right.

Parameters:
  • text (str) – String to chop.
  • step (int) – Interval to chop text.
Returns:

List of chopped characters.

Return type:

list

Example

>>> chop_right('abcdefg', 3)
['a', 'bcd', 'efg']

New in version 3.0.0.

pydash.strings.chars(text)[source]

Split text into a list of single characters.

Parameters:text (str) – String to split up.
Returns:List of individual characters.
Return type:list

Example

>>> chars('onetwo')
['o', 'n', 'e', 't', 'w', 'o']

New in version 3.0.0.

pydash.strings.clean(text)[source]

Trim and replace multiple spaces with a single space.

Parameters:text (str) – String to clean.
Returns:Cleaned string.
Return type:str

Example

>>> clean('a  b   c    d')
'a b c d'

New in version 3.0.0.

pydash.strings.count_substr(text, subtext)[source]

Count the occurrences of subtext in text.

Parameters:
  • text (str) – Source string to count from.
  • subtext (str) – String to count.
Returns:

Number of occurrences of subtext in text.

Return type:

int

Example

>>> count_substr('aabbccddaabbccdd', 'bc')
2

New in version 3.0.0.

pydash.strings.deburr(text)[source]

Deburrs text by converting latin-1 supplementary letters to basic latin letters.

Parameters:text (str) – String to deburr.
Returns:Deburred string.
Return type:str

Example

>>> deburr('déjà vu')
'...
>>> 'deja vu'
'deja vu'

New in version 2.0.0.

pydash.strings.decapitalize(text)[source]

Decaptitalizes the first character of text.

Parameters:text (str) – String to decapitalize.
Returns:Decapitalized string.
Return type:str

Example

>>> decapitalize('FOO BAR')
'fOO BAR'

New in version 3.0.0.

pydash.strings.ends_with(text, target, position=None)[source]

Checks if text ends with a given target string.

Parameters:
  • text (str) – String to check.
  • target (str) – String to check for.
  • position (int, optional) – Position to search from. Defaults to end of text.
Returns:

Whether text ends with target.

Return type:

bool

Example

>>> ends_with('abc def', 'def')
True
>>> ends_with('abc def', 4)
False

New in version 1.1.0.

pydash.strings.ensure_ends_with(text, suffix)[source]

Append a given suffix to a string, but only if the source string does not end with that suffix.

Parameters:
  • text (str) – Source string to append suffix to.
  • suffix (str) – String to append to the source string if the source string does not end with suffix.
Returns:

source string possibly extended by suffix.

Return type:

str

Example

>>> ensure_ends_with('foo bar', '!')
'foo bar!'
>>> ensure_ends_with('foo bar!', '!')
'foo bar!'

New in version 2.4.0.

pydash.strings.ensure_starts_with(text, prefix)[source]

Prepend a given prefix to a string, but only if the source string does not start with that prefix.

Parameters:
  • text (str) – Source string to prepend prefix to.
  • suffix (str) – String to prepend to the source string if the source string does not start with prefix.
Returns:

source string possibly prefixed by prefix

Return type:

str

Example

>>> ensure_starts_with('foo bar', 'Oh my! ')
'Oh my! foo bar'
>>> ensure_starts_with('Oh my! foo bar', 'Oh my! ')
'Oh my! foo bar'

New in version 2.4.0.

pydash.strings.escape(text)[source]

Converts the characters &, <, >, ", ', and \` in text to their corresponding HTML entities.

Parameters:text (str) – String to escape.
Returns:HTML escaped string.
Return type:str

Example

>>> escape('"1 > 2 && 3 < 4"')
'&quot;1 &gt; 2 &amp;&amp; 3 &lt; 4&quot;'

New in version 1.0.0.

Changed in version 1.1.0: Moved function to pydash.strings.

pydash.strings.escape_reg_exp(text)[source]

Escapes the RegExp special characters in text.

Parameters:text (str) – String to escape.
Returns:RegExp escaped string.
Return type:str

Example

>>> escape_reg_exp('[()]')
'\\[\\(\\)\\]'

See also

New in version 1.1.0.

pydash.strings.escape_re(text)

Escapes the RegExp special characters in text.

Parameters:text (str) – String to escape.
Returns:RegExp escaped string.
Return type:str

Example

>>> escape_reg_exp('[()]')
'\\[\\(\\)\\]'

See also

New in version 1.1.0.

pydash.strings.explode(text, separator=<pydash.helpers._NoValue object>)

Splits text on separator. If separator not provided, then text is split on whitespace. If separator is falsey, then text is split on every character.

Parameters:
  • text (str) – String to explode.
  • separator (str, optional) – Separator string to split on. Defaults to NoValue.
Returns:

Split string.

Return type:

list

Example

>>> split('one potato, two potatoes, three potatoes, four!')
['one', 'potato,', 'two', 'potatoes,', 'three', 'potatoes,', 'four!']
>>> split('one potato, two potatoes, three potatoes, four!', ',')
['one potato', ' two potatoes', ' three potatoes', ' four!']

See also

New in version 2.0.0.

Changed in version 3.0.0: Changed separator default to NoValue and supported splitting on whitespace by default.

pydash.strings.has_substr(text, subtext)[source]

Returns whether subtext is included in text.

Parameters:
  • text (str) – String to search.
  • subtext (str) – String to search for.
Returns:

Whether subtext is found in text.

Return type:

bool

Example

>>> has_substr('abcdef', 'bc')
True
>>> has_substr('abcdef', 'bb')
False

New in version 3.0.0.

pydash.strings.human_case(text)[source]

Converts text to human case which has only the first letter capitalized and each word separated by a space.

Parameters:text (str) – String to convert.
Returns:String converted to human case.
Return type:str

Example

>>> human_case('abc-def_hij lmn')
'Abc def hij lmn'
>>> human_case('user_id')
'User'

New in version 3.0.0.

pydash.strings.implode(array, separator='')

Joins an iterable into a string using separator between each element.

Parameters:
  • array (iterable) – Iterable to implode.
  • separator (str, optional) – Separator to using when joining. Defaults to ''.
Returns:

Joined string.

Return type:

str

Example

>>> join(['a', 'b', 'c']) == 'abc'
True
>>> join([1, 2, 3, 4], '&') == '1&2&3&4'
True
>>> join('abcdef', '-') == 'a-b-c-d-e-f'
True

See also

New in version 2.0.0.

Changed in version 3.0.0: Modified implode() to have join() as main definition and implode() as alias.

pydash.strings.insert_substr(text, index, subtext)[source]

Insert subtext in text starting at position index.

Parameters:
  • text (str) – String to add substring to.
  • index (int) – String index to insert into.
  • subtext (str) – String to insert.
Returns:

Modified string.

Return type:

str

Example

>>> insert_substr('abcdef', 3, '--')
'abc--def'

New in version 3.0.0.

pydash.strings.join(array, separator='')[source]

Joins an iterable into a string using separator between each element.

Parameters:
  • array (iterable) – Iterable to implode.
  • separator (str, optional) – Separator to using when joining. Defaults to ''.
Returns:

Joined string.

Return type:

str

Example

>>> join(['a', 'b', 'c']) == 'abc'
True
>>> join([1, 2, 3, 4], '&') == '1&2&3&4'
True
>>> join('abcdef', '-') == 'a-b-c-d-e-f'
True

See also

New in version 2.0.0.

Changed in version 3.0.0: Modified implode() to have join() as main definition and implode() as alias.

pydash.strings.js_match(text, reg_exp)[source]

Return list of matches using Javascript style regular expression.

Parameters:
  • text (str) – String to evaluate.
  • reg_exp (str) – Javascript style regular expression.
Returns:

List of matches.

Return type:

list

Example

>>> js_match('aaBBcc', '/bb/')
[]
>>> js_match('aaBBcc', '/bb/i')
['BB']
>>> js_match('aaBBccbb', '/bb/i')
['BB']
>>> js_match('aaBBccbb', '/bb/gi')
['BB', 'bb']

New in version 2.0.0.

Changed in version 3.0.0: Reordered arguments to make text first.

pydash.strings.js_replace(text, reg_exp, repl)[source]

Replace text with repl using Javascript style regular expression to find matches.

Parameters:
  • text (str) – String to evaluate.
  • reg_exp (str) – Javascript style regular expression.
  • repl (str) – Replacement string.
Returns:

Modified string.

Return type:

str

Example

>>> js_replace('aaBBcc', '/bb/', 'X')
'aaBBcc'
>>> js_replace('aaBBcc', '/bb/i', 'X')
'aaXcc'
>>> js_replace('aaBBccbb', '/bb/i', 'X')
'aaXccbb'
>>> js_replace('aaBBccbb', '/bb/gi', 'X')
'aaXccX'

New in version 2.0.0.

Changed in version 3.0.0: Reordered arguments to make text first.

pydash.strings.kebab_case(text)[source]

Converts text to kebab case (a.k.a. spinal case).

Parameters:text (str) – String to convert.
Returns:String converted to kebab case.
Return type:str

Example

>>> kebab_case('a b c_d-e!f')
'a-b-c-d-e-f'

New in version 1.1.0.

pydash.strings.lines(text)[source]

Split lines in text into an array.

Parameters:text (str) – String to split.
Returns:String split by lines.
Return type:list

Example

>>> lines('a\nb\r\nc')
['a', 'b', 'c']

New in version 3.0.0.

pydash.strings.number_format(number, scale=0, decimal_separator='.', order_separator=', ')[source]

Format a number to scale with custom decimal and order separators.

Parameters:
  • number (int|float) – Number to format.
  • scale (int, optional) – Number of decimals to include. Defaults to 0.
  • decimal_separator (str, optional) – Decimal separator to use. Defaults to '.'.
  • order_separator (str, optional) – Order separator to use. Defaults to ','.
Returns:

Formatted number as string.

Return type:

str

Example

>>> number_format(1234.5678)
'1,235'
>>> number_format(1234.5678, 2, ',', '.')
'1.234,57'

New in version 3.0.0.

pydash.strings.pad(text, length, chars=' ')[source]

Pads text on the left and right sides if it is shorter than the given padding length. The chars string may be truncated if the number of padding characters can’t be evenly divided by the padding length.

Parameters:
  • text (str) – String to pad.
  • length (int) – Amount to pad.
  • chars (str, optional) – Characters to pad with. Defaults to " ".
Returns:

Padded string.

Return type:

str

Example

>>> pad('abc', 5)
' abc '
>>> pad('abc', 6, 'x')
'xabcxx'
>>> pad('abc', 5, '...')
'.abc.'

New in version 1.1.0.

Changed in version 3.0.0: Fix handling of multiple chars so that padded string isn’t over padded.

pydash.strings.pad_left(text, length, chars=' ')[source]

Pads text on the left side if it is shorter than the given padding length. The chars string may be truncated if the number of padding characters can’t be evenly divided by the padding length.

Parameters:
  • text (str) – String to pad.
  • length (int) – Amount to pad.
  • chars (str, optional) – Characters to pad with. Defaults to " ".
Returns:

Padded string.

Return type:

str

Example

>>> pad_left('abc', 5)
'  abc'
>>> pad_left('abc', 5, '.')
'..abc'

New in version 1.1.0.

pydash.strings.pad_right(text, length, chars=' ')[source]

Pads text on the right side if it is shorter than the given padding length. The chars string may be truncated if the number of padding characters can’t be evenly divided by the padding length.

Parameters:
  • text (str) – String to pad.
  • length (int) – Amount to pad.
  • chars (str, optional) – Characters to pad with. Defaults to " ".
Returns:

Padded string.

Return type:

str

Example

>>> pad_right('abc', 5)
'abc  '
>>> pad_right('abc', 5, '.')
'abc..'

New in version 1.1.0.

pydash.strings.pascal_case(text, strict=True)[source]

Like camel_case() except the first letter is capitalized.

Parameters:
  • text (str) – String to convert.
  • strict (bool, optional) – Whether to cast rest of string to lower case. Defaults to True.
Returns:

String converted to class case.

Return type:

str

Example

>>> pascal_case('FOO BAR_bAz')
'FooBarBaz'
>>> pascal_case('FOO BAR_bAz', False)
'FooBarBAz'

New in version 3.0.0.

pydash.strings.predecessor(char)[source]

Return the predecessor character of char.

Parameters:char (str) – Character to find the predecessor of.
Returns:Predecessor character.
Return type:str

Example

>>> predecessor('c')
'b'
>>> predecessor('C')
'B'
>>> predecessor('3')
'2'

New in version 3.0.0.

pydash.strings.prune(text, length=0, omission='...')[source]

Like truncate() except it ensures that the pruned string doesn’t exceed the original length, i.e., it avoids half-chopped words when truncating. If the pruned text + omission text is longer than the original text, then the original text is returned.

Parameters:
  • text (str) – String to prune.
  • length (int, optional) – Target prune length. Defaults to 0.
  • omission (str, optional) – Omission text to append to the end of the pruned string. Defaults to '...'.
Returns:

Pruned string.

Return type:

str

Example

>>> prune('Fe fi fo fum', 5)
'Fe fi...'
>>> prune('Fe fi fo fum', 6)
'Fe fi...'
>>> prune('Fe fi fo fum', 7)
'Fe fi...'
>>> prune('Fe fi fo fum', 8, ',,,')
'Fe fi fo,,,'

New in version 3.0.0.

pydash.strings.quote(text, quote_char='"')[source]

Quote a string with another string.

Parameters:
  • text (str) – String to be quoted.
  • quote_char (str, optional) – the quote character. Defaults to ".
Returns:

the quoted string.

Return type:

str

Example

>>> quote('To be or not to be')
'"To be or not to be"'
>>> quote('To be or not to be', "'")
"'To be or not to be'"

New in version 2.4.0.

pydash.strings.re_replace(text, pattern, repl, ignore_case=False, count=0)[source]

Replace occurrences of regex pattern with repl in text. Optionally, ignore case when replacing. Optionally, set count to limit number of replacements.

Parameters:
  • text (str) – String to replace.
  • pattern (str) – String pattern to find and replace.
  • repl (str) – String to substitute pattern with.
  • ignore_clase (bool, optional) – Whether to ignore case when replacing. Defaults to False.
  • count (int, optional) – Maximum number of occurrences to replace. Defaults to 0 which replaces all.
Returns:

Replaced string.

Return type:

str

Example

>>> re_replace('aabbcc', 'b', 'X')
'aaXXcc'
>>> re_replace('aabbcc', 'B', 'X', ignore_case=True)
'aaXXcc'
>>> re_replace('aabbcc', 'b', 'X', count=1)
'aaXbcc'
>>> re_replace('aabbcc', '[ab]', 'X')
'XXXXcc'

New in version 3.0.0.

pydash.strings.repeat(text, n=0)[source]

Repeats the given string n times.

Parameters:
  • text (str) – String to repeat.
  • n (int, optional) – Number of times to repeat the string.
Returns:

Repeated string.

Return type:

str

Example

>>> repeat('.', 5)
'.....'

New in version 1.1.0.

pydash.strings.replace(text, pattern, repl, ignore_case=False, count=0, escape=True)[source]

Replace occurrences of pattern with repl in text. Optionally, ignore case when replacing. Optionally, set count to limit number of replacements.

Parameters:
  • text (str) – String to replace.
  • pattern (str) – String pattern to find and replace.
  • repl (str) – String to substitute pattern with.
  • ignore_clase (bool, optional) – Whether to ignore case when replacing. Defaults to False.
  • count (int, optional) – Maximum number of occurrences to replace. Defaults to 0 which replaces all.
  • escape (bool, optional) – Whether to escape pattern when searching. This is needed if a literal replacement is desired when pattern may contain special regular expression characters. Defaults to True.
Returns:

Replaced string.

Return type:

str

Example

>>> replace('aabbcc', 'b', 'X')
'aaXXcc'
>>> replace('aabbcc', 'B', 'X', ignore_case=True)
'aaXXcc'
>>> replace('aabbcc', 'b', 'X', count=1)
'aaXbcc'
>>> replace('aabbcc', '[ab]', 'X')
'aabbcc'
>>> replace('aabbcc', '[ab]', 'X', escape=False)
'XXXXcc'

New in version 3.0.0.

pydash.strings.separator_case(text, separator)[source]

Splits text on words and joins with separator.

Parameters:
  • text (str) – String to convert.
  • separator (str) – Separator to join words with.
Returns:

Converted string.

Return type:

str

Example

>>> separator_case('a!!b___c.d', '-')
'a-b-c-d'

New in version 3.0.0.

pydash.strings.series_phrase(items, separator=', ', last_separator=' and ', serial=False)[source]

Join items into a grammatical series phrase, e.g., "item1, item2, item3 and item4".

Parameters:
  • items (list) – List of string items to join.
  • separator (str, optional) – Item separator. Defaults to ', '.
  • last_separator (str, optional) – Last item separator. Defaults to ' and '.
  • serial (bool, optional) – Whether to include separator with last_separator when number of items is greater than 2. Defaults to False.
Returns:

Joined string.

Return type:

str

Example

Example:

>>> series_phrase(['apples', 'bananas', 'peaches'])
'apples, bananas and peaches'
>>> series_phrase(['apples', 'bananas', 'peaches'], serial=True)
'apples, bananas, and peaches'
>>> series_phrase(['apples', 'bananas', 'peaches'], '; ', ', or ')
'apples; bananas, or peaches'

New in version 3.0.0.

pydash.strings.series_phrase_serial(items, separator=', ', last_separator=' and ')[source]

Join items into a grammatical series phrase using a serial separator, e.g., "item1, item2, item3, and item4".

Parameters:
  • items (list) – List of string items to join.
  • separator (str, optional) – Item separator. Defaults to ', '.
  • last_separator (str, optional) – Last item separator. Defaults to ' and '.
Returns:

Joined string.

Return type:

str

Example

>>> series_phrase_serial(['apples', 'bananas', 'peaches'])
'apples, bananas, and peaches'

New in version 3.0.0.

pydash.strings.slugify(text, separator='-')[source]

Convert text into an ASCII slug which can be used safely in URLs. Incoming text is converted to unicode and noramlzied using the NFKD form. This results in some accented characters being converted to their ASCII “equivalent” (e.g. é is converted to e). Leading and trailing whitespace is trimmed and any remaining whitespace or other special characters without an ASCII equivalent are replaced with -.

Parameters:
  • text (str) – String to slugify.
  • separator (str, optional) – Separator to use. Defaults to '-'.
Returns:

Slugified string.

Return type:

str

Example

>>> slugify('This is a slug.') == 'this-is-a-slug'
True
>>> slugify('This is a slug.', '+') == 'this+is+a+slug'
True

New in version 3.0.0.

pydash.strings.snake_case(text)[source]

Converts text to snake case.

Parameters:text (str) – String to convert.
Returns:String converted to snake case.
Return type:str

Example

>>> snake_case('This is Snake Case!')
'this_is_snake_case'

See also

New in version 1.1.0.

pydash.strings.split(text, separator=<pydash.helpers._NoValue object>)[source]

Splits text on separator. If separator not provided, then text is split on whitespace. If separator is falsey, then text is split on every character.

Parameters:
  • text (str) – String to explode.
  • separator (str, optional) – Separator string to split on. Defaults to NoValue.
Returns:

Split string.

Return type:

list

Example

>>> split('one potato, two potatoes, three potatoes, four!')
['one', 'potato,', 'two', 'potatoes,', 'three', 'potatoes,', 'four!']
>>> split('one potato, two potatoes, three potatoes, four!', ',')
['one potato', ' two potatoes', ' three potatoes', ' four!']

See also

New in version 2.0.0.

Changed in version 3.0.0: Changed separator default to NoValue and supported splitting on whitespace by default.

pydash.strings.start_case(text)[source]

Convert text to start case.

Parameters:text (str) – String to convert.
Returns:String converted to start case.
Return type:str

Example

>>> start_case("fooBar")
'Foo Bar'

New in version 3.1.0.

pydash.strings.starts_with(text, target, position=0)[source]

Checks if text starts with a given target string.

Parameters:
  • text (str) – String to check.
  • target (str) – String to check for.
  • position (int, optional) – Position to search from. Defaults to beginning of text.
Returns:

Whether text starts with target.

Return type:

bool

Example

>>> starts_with('abcdef', 'a')
True
>>> starts_with('abcdef', 'b')
False
>>> starts_with('abcdef', 'a', 1)
False

New in version 1.1.0.

pydash.strings.strip_tags(text)[source]

Removes all HTML tags from text.

Parameters:text (str) – String to strip.
Returns:String without HTML tags.
Return type:str

Example

>>> strip_tags('<a href="#">Some link</a>')
'Some link'

New in version 3.0.0.

pydash.strings.substr_left(text, subtext)[source]

Searches text from left-to-right for subtext and returns a substring consisting of the characters in text that are to the left of subtext or all string if no match found.

Parameters:
  • text (str) – String to partition.
  • subtext (str) – String to search for.
Returns:

Substring to left of subtext.

Return type:

str

Example

>>> substr_left('abcdefcdg', 'cd')
'ab'

New in version 3.0.0.

pydash.strings.substr_left_end(text, subtext)[source]

Searches text from right-to-left for subtext and returns a substring consisting of the characters in text that are to the left of subtext or all string if no match found.

Parameters:
  • text (str) – String to partition.
  • subtext (str) – String to search for.
Returns:

Substring to left of subtext.

Return type:

str

Example

>>> substr_left_end('abcdefcdg', 'cd')
'abcdef'

New in version 3.0.0.

pydash.strings.substr_right(text, subtext)[source]

Searches text from right-to-left for subtext and returns a substring consisting of the characters in text that are to the right of subtext or all string if no match found.

Parameters:
  • text (str) – String to partition.
  • subtext (str) – String to search for.
Returns:

Substring to right of subtext.

Return type:

str

Example

>>> substr_right('abcdefcdg', 'cd')
'efcdg'

New in version 3.0.0.

pydash.strings.substr_right_end(text, subtext)[source]

Searches text from left-to-right for subtext and returns a substring consisting of the characters in text that are to the right of subtext or all string if no match found.

Parameters:
  • text (str) – String to partition.
  • subtext (str) – String to search for.
Returns:

Substring to right of subtext.

Return type:

str

Example

>>> substr_right_end('abcdefcdg', 'cd')
'g'

New in version 3.0.0.

pydash.strings.successor(char)[source]

Return the successor character of char.

Parameters:char (str) – Character to find the successor of.
Returns:Successor character.
Return type:str

Example

>>> successor('b')
'c'
>>> successor('B')
'C'
>>> successor('2')
'3'

New in version 3.0.0.

pydash.strings.surround(text, wrapper)[source]

Surround a string with another string.

Parameters:
  • text (str) – String to surround with wrapper.
  • wrapper (str) – String by which text is to be surrounded.
Returns:

Surrounded string.

Return type:

str

Example

>>> surround('abc', '"')
'"abc"'
>>> surround('abc', '!')
'!abc!'

New in version 2.4.0.

pydash.strings.swap_case(text)[source]

Swap case of text characters.

Parameters:text (str) – String to swap case.
Returns:String with swapped case.
Return type:str

Example

>>> swap_case('aBcDeF')
'AbCdEf'

New in version 3.0.0.

pydash.strings.title_case(text)[source]

Convert text to title case.

Parameters:text (str) – String to convert.
Returns:String converted to title case.
Return type:str

Example

>>> title_case("bob's shop")
"Bob's Shop"

New in version 3.0.0.

pydash.strings.trim(text, chars=None)[source]

Removes leading and trailing whitespace or specified characters from text.

Parameters:
  • text (str) – String to trim.
  • chars (str, optional) – Specific characters to remove.
Returns:

Trimmed string.

Return type:

str

Example

>>> trim('  abc efg\r\n ')
'abc efg'

New in version 1.1.0.

pydash.strings.trim_left(text, chars=None)[source]

Removes leading whitespace or specified characters from text.

Parameters:
  • text (str) – String to trim.
  • chars (str, optional) – Specific characters to remove.
Returns:

Trimmed string.

Return type:

str

Example

>>> trim_left('  abc efg\r\n ')
'abc efg\r\n '

New in version 1.1.0.

pydash.strings.trim_right(text, chars=None)[source]

Removes trailing whitespace or specified characters from text.

Parameters:
  • text (str) – String to trim.
  • chars (str, optional) – Specific characters to remove.
Returns:

Trimmed string.

Return type:

str

Example

>>> trim_right('  abc efg\r\n ')
'  abc efg'

New in version 1.1.0.

pydash.strings.trunc(text, length=30, omission='...', separator=None)

Truncates text if it is longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to ....

Parameters:
  • text (str) – String to truncate.
  • length (int, optional) – Maximum string length. Defaults to 30.
  • omission (str, optional) – String to indicate text is omitted.
  • separator (mixed, optional) – Separator pattern to truncate to.
Returns:

Truncated string.

Return type:

str

Example

>>> truncate('hello world', 5)
'he...'
>>> truncate('hello world', 5, '..')
'hel..'
>>> truncate('hello world', 10)
'hello w...'
>>> truncate('hello world', 10, separator=' ')
'hello...'

See also

New in version 1.1.0.

Changed in version 3.0.0: Made truncate() main function definition and added trunc() as alias.

pydash.strings.truncate(text, length=30, omission='...', separator=None)[source]

Truncates text if it is longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to ....

Parameters:
  • text (str) – String to truncate.
  • length (int, optional) – Maximum string length. Defaults to 30.
  • omission (str, optional) – String to indicate text is omitted.
  • separator (mixed, optional) – Separator pattern to truncate to.
Returns:

Truncated string.

Return type:

str

Example

>>> truncate('hello world', 5)
'he...'
>>> truncate('hello world', 5, '..')
'hel..'
>>> truncate('hello world', 10)
'hello w...'
>>> truncate('hello world', 10, separator=' ')
'hello...'

See also

New in version 1.1.0.

Changed in version 3.0.0: Made truncate() main function definition and added trunc() as alias.

pydash.strings.underscore_case(text)

Converts text to snake case.

Parameters:text (str) – String to convert.
Returns:String converted to snake case.
Return type:str

Example

>>> snake_case('This is Snake Case!')
'this_is_snake_case'

See also

New in version 1.1.0.

pydash.strings.unescape(text)[source]

The inverse of escape(). This method converts the HTML entities &amp;, &lt;, &gt;, &quot;, &#39;, and &#96; in text to their corresponding characters.

Parameters:text (str) – String to unescape.
Returns:HTML unescaped string.
Return type:str

Example

>>> results = unescape('&quot;1 &gt; 2 &amp;&amp; 3 &lt; 4&quot;')
>>> results == '"1 > 2 && 3 < 4"'
True

New in version 1.0.0.

Changed in version 1.1.0: Moved to pydash.strings.

pydash.strings.unquote(text, quote_char='"')[source]

Unquote text by removing quote_char if text begins and ends with it.

Parameters:text (str) – String to unquote.
Returns:Unquoted string.
Return type:str

Example

>>> unquote('"abc"')
'abc'
>>> unquote('"abc"', '#')
'"abc"'
>>> unquote('#abc', '#')
'#abc'
>>> unquote('#abc#', '#')
'abc'

New in version 3.0.0.

pydash.strings.url(*paths, **params)[source]

Combines a series of URL paths into a single URL. Optionally, pass in keyword arguments to append query parameters.

Parameters:paths (str) – URL paths to combine.
Keyword Arguments:
 params (str, optional) – Query parameters.
Returns:URL string.
Return type:str

Example

>>> link = url('a', 'b', ['c', 'd'], '/', q='X', y='Z')
>>> path, params = link.split('?')
>>> path == 'a/b/c/d/'
True
>>> set(params.split('&')) == set(['q=X', 'y=Z'])
True

New in version 2.2.0.

pydash.strings.words(text, pattern=None)[source]

Return list of words contained in text.

Parameters:
  • text (str) – String to split.
  • pattern (str, optional) – Custom pattern to split words on. Defaults to None.
Returns:

List of words.

Return type:

list

Example

>>> words('a b, c; d-e')
['a', 'b', 'c', 'd', 'e']
>>> words('fred, barney, & pebbles', '/[^, ]+/g')
['fred', 'barney', '&', 'pebbles']

New in version 2.0.0.

Changed in version 3.2.0: Added pattern argument.

Changed in version 3.2.0: Improved matching for one character words.

Utilities

Utility functions.

New in version 1.0.0.

pydash.utilities.attempt(func, *args, **kargs)[source]

Attempts to execute func, returning either the result or the caught error object.

Parameters:func (function) – The function to attempt.
Returns:Returns the func result or error object.
Return type:mixed

Example

>>> results = attempt(lambda x: x/0, 1)
>>> assert isinstance(results, ZeroDivisionError)

New in version 1.1.0.

pydash.utilities.constant(value)[source]

Creates a function that returns value.

Parameters:value (mixed) – Constant value to return.
Returns:Function that always returns value.
Return type:function

Example

>>> pi = constant(3.14)
>>> pi() == 3.14
True

New in version 1.0.0.

pydash.utilities.callback(func)

Return a pydash style callback. If func is a property name the created callback will return the property value for a given element. If func is an object the created callback will return True for elements that contain the equivalent object properties, otherwise it will return False.

Parameters:func (mixed) – Object to create callback function from.
Returns:Callback function.
Return type:function

Example

>>> get_data = iteratee('data')
>>> get_data({'data': [1, 2, 3]})
[1, 2, 3]
>>> is_active = iteratee({'active': True})
>>> is_active({'active': True})
True
>>> is_active({'active': 0})
False
>>> iteratee(['a', 5])({'a': 5})
True
>>> iteratee(['a.b'])({'a.b': 5})
5
>>> iteratee('a.b')({'a': {'b': 5}})
5
>>> iteratee(lambda a, b: a + b)(1, 2)
3
>>> ident = iteratee(None)
>>> ident('a')
'a'
>>> ident(1, 2, 3)
1

See also

New in version 1.0.0.

Changed in version 2.0.0: Renamed create_callback() to iteratee().

Changed in version 3.0.0: Made pluck style callback support deep property access.

Changed in version 3.1.0: - Added support for shallow pluck style property access via single item list/tuple. - Added support for matches property style callback via two item list/tuple.

pydash.utilities.deep_property(path)[source]

Creates a pydash.collections.pluck() style function, which returns the key value of a given object.

Parameters:key (mixed) – Key value to fetch from object.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> deep_property('a.b.c')({'a': {'b': {'c': 1}}})
1
>>> deep_property('a.1.0.b')({'a': [5, [{'b': 1}]]})
1
>>> deep_property('a.1.0.b')({}) is None
True

See also

New in version 1.0.0.

pydash.utilities.deep_prop(path)

Creates a pydash.collections.pluck() style function, which returns the key value of a given object.

Parameters:key (mixed) – Key value to fetch from object.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> deep_property('a.b.c')({'a': {'b': {'c': 1}}})
1
>>> deep_property('a.1.0.b')({'a': [5, [{'b': 1}]]})
1
>>> deep_property('a.1.0.b')({}) is None
True

See also

New in version 1.0.0.

pydash.utilities.identity(*args)[source]

Return the first argument provided to it.

Parameters:*args (mixed) – Arguments.
Returns:First argument or None.
Return type:mixed

Example

>>> identity(1)
1
>>> identity(1, 2, 3)
1
>>> identity() is None
True

New in version 1.0.0.

pydash.utilities.iteratee(func)[source]

Return a pydash style callback. If func is a property name the created callback will return the property value for a given element. If func is an object the created callback will return True for elements that contain the equivalent object properties, otherwise it will return False.

Parameters:func (mixed) – Object to create callback function from.
Returns:Callback function.
Return type:function

Example

>>> get_data = iteratee('data')
>>> get_data({'data': [1, 2, 3]})
[1, 2, 3]
>>> is_active = iteratee({'active': True})
>>> is_active({'active': True})
True
>>> is_active({'active': 0})
False
>>> iteratee(['a', 5])({'a': 5})
True
>>> iteratee(['a.b'])({'a.b': 5})
5
>>> iteratee('a.b')({'a': {'b': 5}})
5
>>> iteratee(lambda a, b: a + b)(1, 2)
3
>>> ident = iteratee(None)
>>> ident('a')
'a'
>>> ident(1, 2, 3)
1

See also

New in version 1.0.0.

Changed in version 2.0.0: Renamed create_callback() to iteratee().

Changed in version 3.0.0: Made pluck style callback support deep property access.

Changed in version 3.1.0: - Added support for shallow pluck style property access via single item list/tuple. - Added support for matches property style callback via two item list/tuple.

pydash.utilities.matches(source)[source]

Creates a pydash.collections.where() style predicate function which performs a deep comparison between a given object and the source object, returning True if the given object has equivalent property values, else False.

Parameters:source (dict) – Source object used for comparision.
Returns:Function that compares an object to source and returns whether the two objects contain the same items.
Return type:function

Example

>>> matches({'a': {'b': 2}})({'a': {'b': 2, 'c':3}})
True
>>> matches({'a': 1})({'b': 2, 'a': 1})
True
>>> matches({'a': 1})({'b': 2, 'a': 2})
False

New in version 1.0.0.

Changed in version 3.0.0: Use pydash.predicates.is_match() as matching function.

pydash.utilities.matches_property(key, value)[source]

Creates a function that compares the property value of key on a given object to value.

Parameters:
  • key (str) – Object key to match against.
  • value (mixed) – Value to compare to.
Returns:

Function that compares value to an object’s key and returns whether they are equal.

Return type:

function

Example

>>> matches_property('a', 1)({'a': 1, 'b': 2})
True
>>> matches_property(0, 1)([1, 2, 3])
True
>>> matches_property('a', 2)({'a': 1, 'b': 2})
False

New in version 3.1.0.

pydash.utilities.memoize(func, resolver=None)[source]

Creates a function that memoizes the result of func. If resolver is provided it will be used to determine the cache key for storing the result based on the arguments provided to the memoized function. By default, all arguments provided to the memoized function are used as the cache key. The result cache is exposed as the cache property on the memoized function.

Parameters:
  • func (function) – Function to memoize.
  • resolver (function, optional) – Function that returns the cache key to use.
Returns:

Memoized function.

Return type:

function

Example

>>> ident = memoize(identity)
>>> ident(1)
1
>>> ident.cache['(1,){}'] == 1
True
>>> ident(1, 2, 3)
1
>>> ident.cache['(1, 2, 3){}'] == 1
True

New in version 1.0.0.

pydash.utilities.method(path, *args, **kargs)[source]

Creates a function that invokes the method at path on a given object. Any additional arguments are provided to the invoked method.

Parameters:
  • path (str) – Object path of method to invoke.
  • *args (mixed) – Global arguments to apply to method when invoked.
  • **kargs (mixed) – Global keyword argument to apply to method when invoked.
Returns:

Function that invokes method located at path for object.

Return type:

function

Example

>>> obj = {'a': {'b': [None, lambda x: x]}}
>>> echo = method('a.b.1')
>>> echo(obj, 1) == 1
True
>>> echo(obj, 'one') == 'one'
True

New in version 3.3.0.

pydash.utilities.method_of(obj, *args, **kargs)[source]

The opposite of method(). This method creates a function that invokes the method at a given path on object. Any additional arguments are provided to the invoked method.

Parameters:
  • obj (mixed) – The object to query.
  • *args (mixed) – Global arguments to apply to method when invoked.
  • **kargs (mixed) – Global keyword argument to apply to method when invoked.
Returns:

Function that invokes method located at path for object.

Return type:

function

Example

>>> obj = {'a': {'b': [None, lambda x: x]}}
>>> dispatch = method_of(obj)
>>> dispatch('a.b.1', 1) == 1
True
>>> dispatch('a.b.1', 'one') == 'one'
True

New in version 3.3.0.

pydash.utilities.noop(*args, **kargs)[source]

A no-operation function.

New in version 1.0.0.

pydash.utilities.now()[source]

Return the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).

Returns:Milliseconds since Unix epoch.
Return type:int

New in version 1.0.0.

Changed in version 3.0.0: Use datetime module for calculating elapsed time.

pydash.utilities.prop(key)

Creates a pydash.collections.pluck() style function, which returns the key value of a given object.

Parameters:key (mixed) – Key value to fetch from object.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> get_data = prop('data')
>>> get_data({'data': 1})
1
>>> get_data({}) is None
True
>>> get_first = prop(0)
>>> get_first([1, 2, 3])
1

See also

New in version 1.0.0.

pydash.utilities.prop_of(obj)

The inverse of property_(). This method creates a function that returns the key value of a given key on obj.

Parameters:obj (dict|list) – Object to fetch values from.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> getter = prop_of({'a': 1, 'b': 2, 'c': 3})
>>> getter('a')
1
>>> getter('b')
2
>>> getter('x') is None
True

See also

New in version 3.0.0.

pydash.utilities.property_(key)[source]

Creates a pydash.collections.pluck() style function, which returns the key value of a given object.

Parameters:key (mixed) – Key value to fetch from object.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> get_data = prop('data')
>>> get_data({'data': 1})
1
>>> get_data({}) is None
True
>>> get_first = prop(0)
>>> get_first([1, 2, 3])
1

See also

New in version 1.0.0.

pydash.utilities.property_of(obj)[source]

The inverse of property_(). This method creates a function that returns the key value of a given key on obj.

Parameters:obj (dict|list) – Object to fetch values from.
Returns:Function that returns object’s key value.
Return type:function

Example

>>> getter = prop_of({'a': 1, 'b': 2, 'c': 3})
>>> getter('a')
1
>>> getter('b')
2
>>> getter('x') is None
True

See also

New in version 3.0.0.

pydash.utilities.random(start=0, stop=1, floating=False)[source]

Produces a random number between start and stop (inclusive). If only one argument is provided a number between 0 and the given number will be returned. If floating is truthy or either start or stop are floats a floating-point number will be returned instead of an integer.

Parameters:
  • start (int) – Minimum value.
  • stop (int) – Maximum value.
  • floating (bool, optional) – Whether to force random value to float. Default is False.
Returns:

Random value.

Return type:

int|float

Example

>>> 0 <= random() <= 1
True
>>> 5 <= random(5, 10) <= 10
True
>>> isinstance(random(floating=True), float)
True

New in version 1.0.0.

pydash.utilities.range_(*args)[source]

Creates a list of numbers (positive and/or negative) progressing from start up to but not including end. If start is less than stop a zero-length range is created unless a negative step is specified.

Parameters:
  • stop (int) – Integer - 1 to stop at. Defaults to 1.
  • start (int, optional) – Integer to start with. Defaults to 0.
  • step (int, optional) – If positive the last element is the largest start + i * step less than stop. If negative the last element is the smallest start + i * step greater than stop. Defaults to 1.
Returns:

List of integers in range

Return type:

list

Example

>>> list(range_(5))
[0, 1, 2, 3, 4]
>>> list(range_(1, 4))
[1, 2, 3]
>>> list(range_(0, 6, 2))
[0, 2, 4]

New in version 1.0.0.

Changed in version 1.1.0: Moved to pydash.uilities.

Changed in version 3.0.0: Return generator instead of list.

pydash.utilities.result(obj, key, default=None)[source]

Return the value of property key on obj. If key value is a function it will be invoked and its result returned, else the property value is returned. If obj is falsey then default is returned.

Parameters:
  • obj (list|dict) – Object to retrieve result from.
  • key (mixed) – Key or index to get result from.
  • default (mixed, optional) – Default value to return if obj is falsey. Defaults to None.
Returns:

Result of obj[key] or None.

Return type:

mixed

Example

>>> result({'a': 1, 'b': lambda: 2}, 'a')
1
>>> result({'a': 1, 'b': lambda: 2}, 'b')
2
>>> result({'a': 1, 'b': lambda: 2}, 'c') is None
True
>>> result({'a': 1, 'b': lambda: 2}, 'c', default=False)
False

New in version 1.0.0.

Changed in version 2.0.0: Added default argument.

pydash.utilities.times(callback, n)[source]

Executes the callback n times, returning a list of the results of each callback execution. The callback is invoked with one argument: (index).

Parameters:
  • callback (function) – Function to execute.
  • n (int) – Number of times to execute callback.
Returns:

A list of results from calling callback.

Return type:

list

Example

>>> times(lambda i: i, 5)
[0, 1, 2, 3, 4]

New in version 1.0.0.

Changed in version 3.0.0: Reordered arguments to make callback first.

pydash.utilities.unique_id(prefix=None)[source]

Generates a unique ID. If prefix is provided the ID will be appended to it.

Parameters:prefix (str, optional) – String prefix to prepend to ID value.
Returns:ID value.
Return type:str

Example

>>> unique_id()
'1'
>>> unique_id('id_')
'id_2'
>>> unique_id()
'3'

New in version 1.0.0.