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 ---------- iterable : `abc.collections.Iterable` instance Any object t
(iterable)
| 143 | |
| 144 | |
| 145 | def arbitrary_element(iterable): |
| 146 | """Returns an arbitrary element of `iterable` without removing it. |
| 147 | |
| 148 | This is most useful for "peeking" at an arbitrary element of a set, |
| 149 | but can be used for any list, dictionary, etc., as well. |
| 150 | |
| 151 | Parameters |
| 152 | ---------- |
| 153 | iterable : `abc.collections.Iterable` instance |
| 154 | Any object that implements ``__iter__``, e.g. set, dict, list, tuple, |
| 155 | etc. |
| 156 | |
| 157 | Returns |
| 158 | ------- |
| 159 | The object that results from ``next(iter(iterable))`` |
| 160 | |
| 161 | Raises |
| 162 | ------ |
| 163 | ValueError |
| 164 | If `iterable` is an iterator (because the current implementation of |
| 165 | this function would consume an element from the iterator). |
| 166 | |
| 167 | Examples |
| 168 | -------- |
| 169 | Arbitrary elements from common Iterable objects: |
| 170 | |
| 171 | >>> nx.utils.arbitrary_element([1, 2, 3]) # list |
| 172 | 1 |
| 173 | >>> nx.utils.arbitrary_element((1, 2, 3)) # tuple |
| 174 | 1 |
| 175 | >>> nx.utils.arbitrary_element({1, 2, 3}) # set |
| 176 | 1 |
| 177 | >>> d = {k: v for k, v in zip([1, 2, 3], [3, 2, 1])} |
| 178 | >>> nx.utils.arbitrary_element(d) # dict_keys |
| 179 | 1 |
| 180 | >>> nx.utils.arbitrary_element(d.values()) # dict values |
| 181 | 3 |
| 182 | |
| 183 | `str` is also an Iterable: |
| 184 | |
| 185 | >>> nx.utils.arbitrary_element("hello") |
| 186 | 'h' |
| 187 | |
| 188 | :exc:`ValueError` is raised if `iterable` is an iterator: |
| 189 | |
| 190 | >>> iterator = iter([1, 2, 3]) # Iterator, *not* Iterable |
| 191 | >>> nx.utils.arbitrary_element(iterator) |
| 192 | Traceback (most recent call last): |
| 193 | ... |
| 194 | ValueError: cannot return an arbitrary item from an iterator |
| 195 | |
| 196 | Notes |
| 197 | ----- |
| 198 | This function does not return a *random* element. If `iterable` is |
| 199 | ordered, sequential calls will return the same value:: |
| 200 | |
| 201 | >>> l = [1, 2, 3] |
| 202 | >>> nx.utils.arbitrary_element(l) |
no outgoing calls
searching dependent graphs…