arbitrary_element

arbitrary_element(iterable)[source]

Returns an arbitrary element of iterable without removing it.

This is most useful for “peeking” at an arbitrary element of a set, but can be used for any list, dictionary, etc., as well.

Parameters
iterableabc.collections.Iterable instance

Any object that implements __iter__, e.g. set, dict, list, tuple, etc.

Returns
The object that results from next(iter(iterable))
Raises
ValueError

If iterable is an iterator (because the current implementation of this function would consume an element from the iterator).

Notes

This function does not return a random element. If iterable is ordered, sequential calls will return the same value:

>>> l = [1, 2, 3]
>>> nx.utils.arbitrary_element(l)
1
>>> nx.utils.arbitrary_element(l)
1

Examples

Arbitrary elements from common Iterable objects:

>>> nx.utils.arbitrary_element([1, 2, 3])  # list
1
>>> nx.utils.arbitrary_element((1, 2, 3))  # tuple
1
>>> nx.utils.arbitrary_element({1, 2, 3})  # set
1
>>> d = {k: v for k, v in zip([1, 2, 3], [3, 2, 1])}
>>> nx.utils.arbitrary_element(d)  # dict_keys
1
>>> nx.utils.arbitrary_element(d.values())   # dict values
3

str is also an Iterable:

>>> nx.utils.arbitrary_element("hello")
'h'

ValueError is raised if iterable is an iterator:

>>> iterator = iter([1, 2, 3])  # Iterator, *not* Iterable
>>> nx.utils.arbitrary_element(iterator)
Traceback (most recent call last):
    ...
ValueError: cannot return an arbitrary item from an iterator