Skip to content

PyoIterable

Bases: Pipeable, Checkable, Iterable[T]

Base trait for all pyochain Iterables.

PyoIterable[T] is the common API surface shared by:

  • eager Collections: Seq, Vec, Set, SetMut, Dict
  • lazy Iterator: Iter

You typically don't instantiate this trait directly; it exists to provide a consistent, fluent interface across all pyochain Iterables.

This is equivalent to inheriting from collections.abc.Iterable[T] (this trait already does), meaning any concrete subclass is an Iterable[T] as soon as it implements the required dunder __iter__().

On top of the standard Iterable protocol, it provides additional pyochain methods for fluent chaining and convenience (Pipeable, Checkable, length(), comparison helpers, aggregations, etc.).

Parameters:

Name Type Description Default
data Iterable[T]

The data to initialize the concrete iterable with.

required

Raises:

Type Description
TypeError

Always raised when instantiating PyoIterable directly.

Source code in src/pyochain/traits/_iterable.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
class PyoIterable[T](Pipeable, Checkable, Iterable[T]):
    """Base trait for all pyochain `Iterables`.

    `PyoIterable[T]` is the common API surface shared by:

    - eager `Collections`: `Seq`, `Vec`, `Set`, `SetMut`, `Dict`
    - lazy `Iterator`: `Iter`

    You typically don't instantiate this trait directly; it exists to provide a
    consistent, fluent interface across all pyochain `Iterables`.

    This is equivalent to inheriting from `collections.abc.Iterable[T]` (this
    trait already does), meaning any concrete subclass is an `Iterable[T]` as
    soon as it implements the required dunder `__iter__()`.

    On top of the standard `Iterable` protocol, it provides additional pyochain
    methods for fluent chaining and convenience (`Pipeable`, `Checkable`,
    `length()`, comparison helpers, aggregations, etc.).


    Args:
        data (Iterable[T]): The data to initialize the concrete iterable with.

    Raises:
        TypeError: Always raised when instantiating `PyoIterable` directly.
    """

    __slots__ = ()

    def __init__(self, data: Iterable[T]) -> None:  # noqa: ARG002
        msg = f"Cannot instantiate {self.__class__.__name__} directly. "
        raise TypeError(msg)

    @classmethod
    def new(cls) -> Self:
        """Create an empty `Iterable`.

        Make sure to specify the type when calling this method, e.g., `Vec[int].new()`.

        Otherwise, `T` will be inferred as `Any`.

        This can be very useful for mutable collections like `Vec` and `Dict`.

        However, this can be handy for immutable collections too, for example for representing failure steps in a pipeline.

        Returns:
            Self: A new empty `Iterable` instance.

        Example:
        ```python
        >>> import pyochain as pc
        >>> data = pc.Vec[int].new()
        >>> data
        Vec()
        >>> # Equivalent to
        >>> data: list[str] = []
        >>> data
        []
        >>> my_dict = pc.Dict[str, int].new()
        >>> my_dict.insert("a", 1)
        NONE
        >>> my_dict
        Dict('a': 1)

        ```
        """
        return cls(())

    def iter(self) -> Iter[T]:
        """Get an `Iter` over the `Iterable`.

        Call this to switch to lazy evaluation.

        Note:
            Calling this method on a class who is itself an `Iterator` has no effect.

        Returns:
            Iter[T]: An `Iterator` over the `Iterable`. The element type is inferred from the actual subclass.

        Example:
        ```python
        >>> import pyochain as pc
        >>> seq = pc.Seq([1, 2, 3])
        >>> iterator = seq.iter()
        >>> iterator.collect()
        Seq(1, 2, 3)
        >>> # iterator is now empty
        >>> iterator.collect()
        Seq()

        ```
        """
        from .._iter import Iter

        return Iter(self)

    def length(self) -> int:
        """Return the length of the `Iterable`.

        Returns:
            int: The count of elements.
        ```python
        >>> import pyochain as pc
        >>> pc.Seq([1, 2]).length()
        2
        >>> pc.Iter(range(5)).length()
        5

        ```
        """
        return cz.itertoolz.count(self.__iter__())

    def join(self: PyoIterable[str], sep: str) -> str:
        """Join all elements of the `Iterable` into a single `str`, with a specified separator.

        Args:
            sep (str): Separator to use between elements.

        Returns:
            str: The joined string.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Seq(["a", "b", "c"]).join("-")
        'a-b-c'

        ```
        """
        return sep.join(self.__iter__())

    def first(self) -> T:
        """Return the first element of the `Iterable`.

        This is similar to `__getitem__` but works on lazy `Iterators`.

        Returns:
            T: The first element of the `Iterable`.

        ```python
        >>> import pyochain as pc
        >>> pc.Seq([9]).first()
        9

        ```
        """
        return cz.itertoolz.first(self.__iter__())

    def second(self) -> T:
        """Return the second element of the `Iterable`.

        This is similar to `__getitem__` but works on lazy `Iterators`.

        Returns:
            T: The second element of the `Iterable`.

        ```python
        >>> import pyochain as pc
        >>> pc.Seq([9, 8]).second()
        8

        ```
        """
        return cz.itertoolz.second(self.__iter__())

    def last(self) -> T:
        """Return the last element of the `Iterable`.

        This is similar to `__getitem__` but works on lazy `Iterators`.

        Returns:
            T: The last element of the `Iterable`.

        ```python
        >>> import pyochain as pc
        >>> pc.Seq([7, 8, 9]).last()
        9

        ```
        """
        return cz.itertoolz.last(self.__iter__())

    def sum[U: int | bool](self: PyoIterable[U]) -> int:
        """Return the sum of the `Iterable`.

        If the `Iterable` is empty, return 0.

        Returns:
            int: The sum of all elements.

        ```python
        >>> import pyochain as pc
        >>> pc.Seq([1, 2, 3]).sum()
        6

        ```
        """
        return sum(self.__iter__())

    def min[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
        """Return the minimum of the `Iterable`.

        The elements of the `Iterable` must support comparison operations.

        For comparing elements using a custom **key** function, use `min_by()` instead.

        If multiple elements are tied for the minimum value, the first one encountered is returned.

        Returns:
            U: The minimum value.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Seq([3, 1, 2]).min()
        1

        ```
        """
        return min(self.__iter__())

    def min_by[U: SupportsRichComparison[Any]](self, *, key: Callable[[T], U]) -> T:
        """Return the minimum element of the `Iterable` using a custom **key** function.

        If multiple elements are tied for the minimum value, the first one encountered is returned.

        Args:
            key (Callable[[T], U]): Function to extract a comparison key from each element.

        Returns:
            T: The element with the minimum key value.

        Example:
        ```python
        >>> import pyochain as pc
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class Foo:
        ...     x: int
        ...     y: str
        >>>
        >>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(4, "c")]).min_by(key=lambda f: f.x)
        Foo(x=1, y='b')
        >>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(1, "c")]).min_by(key=lambda f: f.x)
        Foo(x=1, y='b')

        ```
        """
        return min(self.__iter__(), key=key)

    def max[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
        """Return the maximum element of the `Iterable`.

        The elements of the `Iterable` must support comparison operations.

        For comparing elements using a custom **key** function, use `max_by()` instead.

        If multiple elements are tied for the maximum value, the first one encountered is returned.

        Returns:
            U: The maximum value.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Seq([3, 1, 2]).max()
        3

        ```
        """
        return max(self.__iter__())

    def max_by[U: SupportsRichComparison[Any]](self, *, key: Callable[[T], U]) -> T:
        """Return the maximum element of the `Iterable` using a custom **key** function.

        If multiple elements are tied for the maximum value, the first one encountered is returned.

        Args:
            key (Callable[[T], U]): Function to extract a comparison key from each element.

        Returns:
            T: The element with the maximum key value.

        Example:
        ```python
        >>> import pyochain as pc
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class Foo:
        ...     x: int
        ...     y: str
        >>>
        >>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(4, "c")]).max_by(key=lambda f: f.x)
        Foo(x=4, y='c')
        >>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(3, "c")]).max_by(key=lambda f: f.x)
        Foo(x=3, y='b')

        ```
        """
        return max(self.__iter__(), key=key)

    def all(self, predicate: Callable[[T], bool] | None = None) -> bool:
        """Tests if every element of the `Iterable` is truthy.

        `Iter.all()` can optionally take a closure that returns true or false.

        It applies this closure to each element of the `Iterable`, and if they all return true, then so does `Iter.all()`.

        If any of them return false, it returns false.

        An empty `Iterable` returns true.

        Args:
            predicate (Callable[[T], bool] | None): Optional function to evaluate each item.

        Returns:
            bool: True if all elements match the predicate, False otherwise.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Seq([1, True]).all()
        True
        >>> pc.Seq([]).all()
        True
        >>> pc.Seq([1, 0]).all()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>> pc.Seq([2, 4, 6]).all(is_even)
        True

        ```
        """
        if predicate is None:
            return all(self.__iter__())
        return all(predicate(x) for x in self.__iter__())

    def any(self, predicate: Callable[[T], bool] | None = None) -> bool:
        """Tests if any element of the `Iterable` is truthy.

        `Iter.any()` can optionally take a closure that returns true or false.

        It applies this closure to each element of the `Iterable`, and if any of them return true, then so does `Iter.any()`.
        If they all return false, it returns false.

        An empty iterator returns false.

        Args:
            predicate (Callable[[T], bool] | None): Optional function to evaluate each item.

        Returns:
            bool: True if any element matches the predicate, False otherwise.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Seq([0, 1]).any()
        True
        >>> pc.Seq(range(0)).any()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>> pc.Seq([1, 3, 4]).any(is_even)
        True

        ```
        """
        if predicate is None:
            return any(self.__iter__())
        return any(predicate(x) for x in self.__iter__())

all(predicate=None)

Tests if every element of the Iterable is truthy.

Iter.all() can optionally take a closure that returns true or false.

It applies this closure to each element of the Iterable, and if they all return true, then so does Iter.all().

If any of them return false, it returns false.

An empty Iterable returns true.

Parameters:

Name Type Description Default
predicate Callable[[T], bool] | None

Optional function to evaluate each item.

None

Returns:

Name Type Description
bool bool

True if all elements match the predicate, False otherwise.

Example:

>>> import pyochain as pc
>>> pc.Seq([1, True]).all()
True
>>> pc.Seq([]).all()
True
>>> pc.Seq([1, 0]).all()
False
>>> def is_even(x: int) -> bool:
...     return x % 2 == 0
>>> pc.Seq([2, 4, 6]).all(is_even)
True

Source code in src/pyochain/traits/_iterable.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def all(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if every element of the `Iterable` is truthy.

    `Iter.all()` can optionally take a closure that returns true or false.

    It applies this closure to each element of the `Iterable`, and if they all return true, then so does `Iter.all()`.

    If any of them return false, it returns false.

    An empty `Iterable` returns true.

    Args:
        predicate (Callable[[T], bool] | None): Optional function to evaluate each item.

    Returns:
        bool: True if all elements match the predicate, False otherwise.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([1, True]).all()
    True
    >>> pc.Seq([]).all()
    True
    >>> pc.Seq([1, 0]).all()
    False
    >>> def is_even(x: int) -> bool:
    ...     return x % 2 == 0
    >>> pc.Seq([2, 4, 6]).all(is_even)
    True

    ```
    """
    if predicate is None:
        return all(self.__iter__())
    return all(predicate(x) for x in self.__iter__())

any(predicate=None)

Tests if any element of the Iterable is truthy.

Iter.any() can optionally take a closure that returns true or false.

It applies this closure to each element of the Iterable, and if any of them return true, then so does Iter.any(). If they all return false, it returns false.

An empty iterator returns false.

Parameters:

Name Type Description Default
predicate Callable[[T], bool] | None

Optional function to evaluate each item.

None

Returns:

Name Type Description
bool bool

True if any element matches the predicate, False otherwise.

Example:

>>> import pyochain as pc
>>> pc.Seq([0, 1]).any()
True
>>> pc.Seq(range(0)).any()
False
>>> def is_even(x: int) -> bool:
...     return x % 2 == 0
>>> pc.Seq([1, 3, 4]).any(is_even)
True

Source code in src/pyochain/traits/_iterable.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def any(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if any element of the `Iterable` is truthy.

    `Iter.any()` can optionally take a closure that returns true or false.

    It applies this closure to each element of the `Iterable`, and if any of them return true, then so does `Iter.any()`.
    If they all return false, it returns false.

    An empty iterator returns false.

    Args:
        predicate (Callable[[T], bool] | None): Optional function to evaluate each item.

    Returns:
        bool: True if any element matches the predicate, False otherwise.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([0, 1]).any()
    True
    >>> pc.Seq(range(0)).any()
    False
    >>> def is_even(x: int) -> bool:
    ...     return x % 2 == 0
    >>> pc.Seq([1, 3, 4]).any(is_even)
    True

    ```
    """
    if predicate is None:
        return any(self.__iter__())
    return any(predicate(x) for x in self.__iter__())

first()

Return the first element of the Iterable.

This is similar to __getitem__ but works on lazy Iterators.

Returns:

Name Type Description
T T

The first element of the Iterable.

>>> import pyochain as pc
>>> pc.Seq([9]).first()
9
Source code in src/pyochain/traits/_iterable.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def first(self) -> T:
    """Return the first element of the `Iterable`.

    This is similar to `__getitem__` but works on lazy `Iterators`.

    Returns:
        T: The first element of the `Iterable`.

    ```python
    >>> import pyochain as pc
    >>> pc.Seq([9]).first()
    9

    ```
    """
    return cz.itertoolz.first(self.__iter__())

iter()

Get an Iter over the Iterable.

Call this to switch to lazy evaluation.

Note

Calling this method on a class who is itself an Iterator has no effect.

Returns:

Type Description
Iter[T]

Iter[T]: An Iterator over the Iterable. The element type is inferred from the actual subclass.

Example:

>>> import pyochain as pc
>>> seq = pc.Seq([1, 2, 3])
>>> iterator = seq.iter()
>>> iterator.collect()
Seq(1, 2, 3)
>>> # iterator is now empty
>>> iterator.collect()
Seq()

Source code in src/pyochain/traits/_iterable.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def iter(self) -> Iter[T]:
    """Get an `Iter` over the `Iterable`.

    Call this to switch to lazy evaluation.

    Note:
        Calling this method on a class who is itself an `Iterator` has no effect.

    Returns:
        Iter[T]: An `Iterator` over the `Iterable`. The element type is inferred from the actual subclass.

    Example:
    ```python
    >>> import pyochain as pc
    >>> seq = pc.Seq([1, 2, 3])
    >>> iterator = seq.iter()
    >>> iterator.collect()
    Seq(1, 2, 3)
    >>> # iterator is now empty
    >>> iterator.collect()
    Seq()

    ```
    """
    from .._iter import Iter

    return Iter(self)

join(sep)

Join all elements of the Iterable into a single str, with a specified separator.

Parameters:

Name Type Description Default
sep str

Separator to use between elements.

required

Returns:

Name Type Description
str str

The joined string.

Example:

>>> import pyochain as pc
>>> pc.Seq(["a", "b", "c"]).join("-")
'a-b-c'

Source code in src/pyochain/traits/_iterable.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def join(self: PyoIterable[str], sep: str) -> str:
    """Join all elements of the `Iterable` into a single `str`, with a specified separator.

    Args:
        sep (str): Separator to use between elements.

    Returns:
        str: The joined string.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq(["a", "b", "c"]).join("-")
    'a-b-c'

    ```
    """
    return sep.join(self.__iter__())

last()

Return the last element of the Iterable.

This is similar to __getitem__ but works on lazy Iterators.

Returns:

Name Type Description
T T

The last element of the Iterable.

>>> import pyochain as pc
>>> pc.Seq([7, 8, 9]).last()
9
Source code in src/pyochain/traits/_iterable.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def last(self) -> T:
    """Return the last element of the `Iterable`.

    This is similar to `__getitem__` but works on lazy `Iterators`.

    Returns:
        T: The last element of the `Iterable`.

    ```python
    >>> import pyochain as pc
    >>> pc.Seq([7, 8, 9]).last()
    9

    ```
    """
    return cz.itertoolz.last(self.__iter__())

length()

Return the length of the Iterable.

Returns:

Name Type Description
int int

The count of elements.

>>> import pyochain as pc
>>> pc.Seq([1, 2]).length()
2
>>> pc.Iter(range(5)).length()
5
Source code in src/pyochain/traits/_iterable.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def length(self) -> int:
    """Return the length of the `Iterable`.

    Returns:
        int: The count of elements.
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([1, 2]).length()
    2
    >>> pc.Iter(range(5)).length()
    5

    ```
    """
    return cz.itertoolz.count(self.__iter__())

max()

Return the maximum element of the Iterable.

The elements of the Iterable must support comparison operations.

For comparing elements using a custom key function, use max_by() instead.

If multiple elements are tied for the maximum value, the first one encountered is returned.

Returns:

Name Type Description
U U

The maximum value.

Example:

>>> import pyochain as pc
>>> pc.Seq([3, 1, 2]).max()
3

Source code in src/pyochain/traits/_iterable.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def max[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
    """Return the maximum element of the `Iterable`.

    The elements of the `Iterable` must support comparison operations.

    For comparing elements using a custom **key** function, use `max_by()` instead.

    If multiple elements are tied for the maximum value, the first one encountered is returned.

    Returns:
        U: The maximum value.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([3, 1, 2]).max()
    3

    ```
    """
    return max(self.__iter__())

max_by(*, key)

Return the maximum element of the Iterable using a custom key function.

If multiple elements are tied for the maximum value, the first one encountered is returned.

Parameters:

Name Type Description Default
key Callable[[T], U]

Function to extract a comparison key from each element.

required

Returns:

Name Type Description
T T

The element with the maximum key value.

Example:

>>> import pyochain as pc
>>> from dataclasses import dataclass
>>> @dataclass
... class Foo:
...     x: int
...     y: str
>>>
>>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(4, "c")]).max_by(key=lambda f: f.x)
Foo(x=4, y='c')
>>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(3, "c")]).max_by(key=lambda f: f.x)
Foo(x=3, y='b')

Source code in src/pyochain/traits/_iterable.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def max_by[U: SupportsRichComparison[Any]](self, *, key: Callable[[T], U]) -> T:
    """Return the maximum element of the `Iterable` using a custom **key** function.

    If multiple elements are tied for the maximum value, the first one encountered is returned.

    Args:
        key (Callable[[T], U]): Function to extract a comparison key from each element.

    Returns:
        T: The element with the maximum key value.

    Example:
    ```python
    >>> import pyochain as pc
    >>> from dataclasses import dataclass
    >>> @dataclass
    ... class Foo:
    ...     x: int
    ...     y: str
    >>>
    >>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(4, "c")]).max_by(key=lambda f: f.x)
    Foo(x=4, y='c')
    >>> pc.Seq([Foo(2, "a"), Foo(3, "b"), Foo(3, "c")]).max_by(key=lambda f: f.x)
    Foo(x=3, y='b')

    ```
    """
    return max(self.__iter__(), key=key)

min()

Return the minimum of the Iterable.

The elements of the Iterable must support comparison operations.

For comparing elements using a custom key function, use min_by() instead.

If multiple elements are tied for the minimum value, the first one encountered is returned.

Returns:

Name Type Description
U U

The minimum value.

Example:

>>> import pyochain as pc
>>> pc.Seq([3, 1, 2]).min()
1

Source code in src/pyochain/traits/_iterable.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def min[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
    """Return the minimum of the `Iterable`.

    The elements of the `Iterable` must support comparison operations.

    For comparing elements using a custom **key** function, use `min_by()` instead.

    If multiple elements are tied for the minimum value, the first one encountered is returned.

    Returns:
        U: The minimum value.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([3, 1, 2]).min()
    1

    ```
    """
    return min(self.__iter__())

min_by(*, key)

Return the minimum element of the Iterable using a custom key function.

If multiple elements are tied for the minimum value, the first one encountered is returned.

Parameters:

Name Type Description Default
key Callable[[T], U]

Function to extract a comparison key from each element.

required

Returns:

Name Type Description
T T

The element with the minimum key value.

Example:

>>> import pyochain as pc
>>> from dataclasses import dataclass
>>> @dataclass
... class Foo:
...     x: int
...     y: str
>>>
>>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(4, "c")]).min_by(key=lambda f: f.x)
Foo(x=1, y='b')
>>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(1, "c")]).min_by(key=lambda f: f.x)
Foo(x=1, y='b')

Source code in src/pyochain/traits/_iterable.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def min_by[U: SupportsRichComparison[Any]](self, *, key: Callable[[T], U]) -> T:
    """Return the minimum element of the `Iterable` using a custom **key** function.

    If multiple elements are tied for the minimum value, the first one encountered is returned.

    Args:
        key (Callable[[T], U]): Function to extract a comparison key from each element.

    Returns:
        T: The element with the minimum key value.

    Example:
    ```python
    >>> import pyochain as pc
    >>> from dataclasses import dataclass
    >>> @dataclass
    ... class Foo:
    ...     x: int
    ...     y: str
    >>>
    >>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(4, "c")]).min_by(key=lambda f: f.x)
    Foo(x=1, y='b')
    >>> pc.Seq([Foo(2, "a"), Foo(1, "b"), Foo(1, "c")]).min_by(key=lambda f: f.x)
    Foo(x=1, y='b')

    ```
    """
    return min(self.__iter__(), key=key)

new() classmethod

Create an empty Iterable.

Make sure to specify the type when calling this method, e.g., Vec[int].new().

Otherwise, T will be inferred as Any.

This can be very useful for mutable collections like Vec and Dict.

However, this can be handy for immutable collections too, for example for representing failure steps in a pipeline.

Returns:

Name Type Description
Self Self

A new empty Iterable instance.

Example:

>>> import pyochain as pc
>>> data = pc.Vec[int].new()
>>> data
Vec()
>>> # Equivalent to
>>> data: list[str] = []
>>> data
[]
>>> my_dict = pc.Dict[str, int].new()
>>> my_dict.insert("a", 1)
NONE
>>> my_dict
Dict('a': 1)

Source code in src/pyochain/traits/_iterable.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@classmethod
def new(cls) -> Self:
    """Create an empty `Iterable`.

    Make sure to specify the type when calling this method, e.g., `Vec[int].new()`.

    Otherwise, `T` will be inferred as `Any`.

    This can be very useful for mutable collections like `Vec` and `Dict`.

    However, this can be handy for immutable collections too, for example for representing failure steps in a pipeline.

    Returns:
        Self: A new empty `Iterable` instance.

    Example:
    ```python
    >>> import pyochain as pc
    >>> data = pc.Vec[int].new()
    >>> data
    Vec()
    >>> # Equivalent to
    >>> data: list[str] = []
    >>> data
    []
    >>> my_dict = pc.Dict[str, int].new()
    >>> my_dict.insert("a", 1)
    NONE
    >>> my_dict
    Dict('a': 1)

    ```
    """
    return cls(())

second()

Return the second element of the Iterable.

This is similar to __getitem__ but works on lazy Iterators.

Returns:

Name Type Description
T T

The second element of the Iterable.

>>> import pyochain as pc
>>> pc.Seq([9, 8]).second()
8
Source code in src/pyochain/traits/_iterable.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def second(self) -> T:
    """Return the second element of the `Iterable`.

    This is similar to `__getitem__` but works on lazy `Iterators`.

    Returns:
        T: The second element of the `Iterable`.

    ```python
    >>> import pyochain as pc
    >>> pc.Seq([9, 8]).second()
    8

    ```
    """
    return cz.itertoolz.second(self.__iter__())

sum()

Return the sum of the Iterable.

If the Iterable is empty, return 0.

Returns:

Name Type Description
int int

The sum of all elements.

>>> import pyochain as pc
>>> pc.Seq([1, 2, 3]).sum()
6
Source code in src/pyochain/traits/_iterable.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def sum[U: int | bool](self: PyoIterable[U]) -> int:
    """Return the sum of the `Iterable`.

    If the `Iterable` is empty, return 0.

    Returns:
        int: The sum of all elements.

    ```python
    >>> import pyochain as pc
    >>> pc.Seq([1, 2, 3]).sum()
    6

    ```
    """
    return sum(self.__iter__())