Skip to content

PyoIterator

Bases: PyoIterable[T], Iterator[T], ABC


              flowchart TD
              pyochain.abc._iterator.PyoIterator[PyoIterator]
              pyochain.abc._iterable.PyoIterable[PyoIterable]
              pyochain.rs.Pipeable[Pipeable]
              pyochain.rs.Into[Into]
              pyochain.rs.Inspect[Inspect]
              pyochain.rs.Checkable[Checkable]

                              pyochain.abc._iterable.PyoIterable --> pyochain.abc._iterator.PyoIterator
                                pyochain.rs.Pipeable --> pyochain.abc._iterable.PyoIterable
                                pyochain.rs.Into --> pyochain.rs.Pipeable
                
                pyochain.rs.Inspect --> pyochain.rs.Pipeable
                

                pyochain.rs.Checkable --> pyochain.abc._iterable.PyoIterable
                



              click pyochain.abc._iterator.PyoIterator href "" "pyochain.abc._iterator.PyoIterator"
              click pyochain.abc._iterable.PyoIterable href "" "pyochain.abc._iterable.PyoIterable"
              click pyochain.rs.Pipeable href "" "pyochain.rs.Pipeable"
              click pyochain.rs.Into href "" "pyochain.rs.Into"
              click pyochain.rs.Inspect href "" "pyochain.rs.Inspect"
              click pyochain.rs.Checkable href "" "pyochain.rs.Checkable"
            

Extends PyoIterable[T] and collections.abc.Iterator[T].

  • An Iterable is any object capable of creating an Iterator (i.e., it implements the __iter__() method).
  • An Iterator is an object representing a stream of data, generating the next value with each call to __next__().

Iterators are composable, meaning you can chain operations like map(), filter(), etc., that will simply add a new step to the processing pipeline without executing it.

Thus, it can be considered akin to a SQL query: An Iterator represents a recipe for how to process the data.

Terminal operations (like collect(), count(), all(), etc.) will "execute the query" by consuming the Iterator and producing a final result.

This is done by calling __next__() repeatedly until StopIteration is raised, which signals that the Iterator is exhausted.

Once this happened, the Iterator instance is empty and cannot be reused to produce new values.

A high-level way of thinking about how to use Iterators is to create one from a source of data, build a plan, and execute it.

Then, if the result is a new Iterable, you can create a new Iterator from it and repeat the process.

If all of this doesn't sound familiar, it's simply because Python does this in an implicit way.

A for loop will create an Iterator from the provided iterable, and consume it until exhaustion.

For example, a list knows its size, how to access items by index, etc..

But it does not know how to iterate over itself, i.e returns elements one by one and stop once x event happens.

It knows, however, how to create an Iterator object that will handle this.

All concrete subclasses must implement the required Iterator dunder methods:

  • __iter__
  • __next__
Example
>>> from pyochain.abc import PyoIterator
>>> class Count(PyoIterator[int]):
...     def __init__(self, start: int = 0):
...         self.current = start
...
...     def __iter__(self):
...         return self
...
...     def __next__(self):
...         val = self.current
...         self.current += 1
...         return val
>>>
>>> counter = Count(5)
>>> counter.next()
Some(5)
>>> counter.next()
Some(6)
>>> counter.iter().take(3).collect()
Seq(7, 8, 9)
Source code in src/pyochain/abc/_iterator.py
  33
  34
  35
  36
  37
  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
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
class PyoIterator[T](PyoIterable[T], Iterator[T], ABC):
    """Extends `PyoIterable[T]` and `collections.abc.Iterator[T]`.

    - An `Iterable` is any object capable of creating an `Iterator` (i.e., it implements the `__iter__()` method).
    - An `Iterator` is an object representing a stream of data, generating the next value with each call to `__next__()`.

    `Iterator`s are composable, meaning you can chain operations like `map()`, `filter()`, etc., that will simply add a new step to the processing pipeline without executing it.

    Thus, it can be considered akin to a SQL query: An `Iterator` represents a recipe for how to process the data.

    Terminal operations (like `collect()`, `count()`, `all()`, etc.) will "execute the query" by consuming the `Iterator` and producing a final result.

    This is done by calling `__next__()` repeatedly until `StopIteration` is raised, which signals that the `Iterator` is exhausted.

    Once this happened, the `Iterator` instance is empty and cannot be reused to produce new values.

    A high-level way of thinking about how to use `Iterators` is to create one from a source of data, build a plan, and execute it.

    Then, if the result is a new `Iterable`, you can create a new `Iterator` from it and repeat the process.

    If all of this doesn't sound familiar, it's simply because Python does this in an implicit way.

    A *for loop* will create an `Iterator` from the provided iterable, and consume it until exhaustion.

    For example, a `list` knows its size, how to access items by index, etc..

    But it does not know how to iterate over itself, i.e returns elements one by one and stop once x event happens.

    It knows, however, how to create an `Iterator` object that will handle this.

    All concrete subclasses must implement the required `Iterator` dunder methods:

    - `__iter__`
    - `__next__`

    Example:
        ```python
        >>> from pyochain.abc import PyoIterator
        >>> class Count(PyoIterator[int]):
        ...     def __init__(self, start: int = 0):
        ...         self.current = start
        ...
        ...     def __iter__(self):
        ...         return self
        ...
        ...     def __next__(self):
        ...         val = self.current
        ...         self.current += 1
        ...         return val
        >>>
        >>> counter = Count(5)
        >>> counter.next()
        Some(5)
        >>> counter.next()
        Some(6)
        >>> counter.iter().take(3).collect()
        Seq(7, 8, 9)

        ```
    """

    # pyrefly: ignore [implicit-any-attribute]
    __slots__ = ()  # pyright: ignore[reportUnannotatedClassAttribute]

    @no_doctest
    def _from_iterable(self, iterable: Iterable[T]) -> Self:
        """Internal constructor.

        Since some methods returns a new `PyoIterator`, we use this, with the assumption that the concrete subclass has an `__init__` that can accept an `Iterable[T]`.

        If you want to implement a different constructor, you will need to override this method with one that can construct new instances from an iterable argument.

        Args:
            iterable (Iterable[T]): An iterable to create the new `PyoIterator` from.

        Returns:
            Self: A new instance of the concrete `PyoIterator` subclass.

        See Also:
            This is how python standard library handle `collections::abc::Set`, see the first point below `Notes on using Set [...]`:

            https://docs.python.org/3/library/collections.abc.html#examples-and-recipes

        """
        return self.__class__(iterable)  # pyright: ignore[reportCallIssue]

    def count(self) -> int:
        """Consume the `Iterator` and return the number of elements it contained.

        Returns:
            int: The count of elements.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> data = Iter((1, 2, 3))
            >>> data.count()
            3
            >>> # data is now empty
            >>> data.count()
            0

            ```
        """
        return tls.length(iter(self))

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

        `PyoIterator::.all` can optionally take a closure that returns true or false.

        It applies this closure to each element of the `Iterator`, and if they all return true, then so does `PyoIterator::.all`.

        If any of them return false, it returns false.

        An empty `Iterator` 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
            >>> from pyochain import Iter
            >>> Iter((1, True)).all()
            True
            >>> Iter(()).all()
            True
            >>> Iter((1, 0)).all()
            False
            >>> def is_even(x: int) -> bool:
            ...     return x % 2 == 0
            >>>
            >>> Iter((2, 4, 6)).all(is_even)
            True
            >>> Iter(("a", "", "c")).all()
            False
            >>> Iter((1, None, 3)).all()
            False

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

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

        `PyoIterator::.any` can optionally take a closure that returns true or false.

        It applies this closure to each element of the `Iterator`, and if any of them return true, then so does `PyoIterator::.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
            >>> from pyochain import Iter, Range
            >>> Iter((0, 1)).any()
            True
            >>> Range(0, 0).iter().any()
            False
            >>> def is_even(x: int) -> bool:
            ...     return x % 2 == 0
            >>> Iter((1, 3, 4)).any(is_even)
            True

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

    def nth(self, n: int) -> Option[T]:
        """Return the nth item of the `Iterable` at the specified *n*.

        This is similar to `__getitem__` but for lazy `Iterators`.

        If *n* is out of bounds, returns `NONE`.

        Args:
            n (int): The index of the item to retrieve.

        Returns:
            Option[T]: `Some(item)` at the specified *n*.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter([10, 20]).nth(1)
            Some(20)
            >>> Iter([10, 20]).nth(3)
            NONE

            ```
        """
        try:
            return Some(next(itertools.islice(iter(self), n, n + 1)))
        except StopIteration:
            return NONE

    def eq(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** and *other* contain the same items in the same order.

        Comparison is performed element by element.

        Two `Iterable`s are equal only if:

        - every compared pair of elements is equal
        - and both iterables are exhausted at the same time

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` when both iterables yield the same sequence of values.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter((1, 2, 3)).eq(Seq((1, 2, 3)))
            True
            >>> Iter((1, 2, 3)).eq((1, 2, 4))
            False
            >>> Iter((1, 2, 3)).eq((1, 2))
            False
            >>> Iter((1, 2)).eq((1, 2, 3))
            False

            ```
        """
        return tls.eq(iter(self), other)

    def ne(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** and *other* differ in value or length.

        This is the logical opposite of `eq()`.

        The result becomes `True` as soon as:

        - a pair of compared elements is not equal
        - or one iterable ends before the other

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` when the two iterables are not equal.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter((1, 2, 3)).ne(Seq((1, 2, 3)))
            False
            >>> Iter((1, 2, 3)).ne((1, 2, 4))
            True
            >>> Iter((1, 2, 3)).ne((1, 2))
            True

            ```
        """
        return tls.ne(iter(self), other)

    def le(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** is lexicographically less than or equal to *other*.

        Comparison is performed element by element, like Python sequence ordering.

        The first differing pair decides the result.

        If all compared elements are equal and one iterable ends first, the shorter iterable is considered smaller.

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` if **self** is smaller than *other*, or equal to it.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2)).le((1, 2, 3))
            True
            >>> Iter((1, 2, 3)).le((1, 2, 3))
            True
            >>> Iter((1, 3)).le((1, 2, 9))
            False

            ```
        """
        return tls.le(iter(self), other)

    def lt(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** is lexicographically strictly less than *other*.

        The first differing pair of elements decides the result.

        If all compared elements are equal, a shorter iterable is strictly smaller than a longer one.

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` if **self** compares strictly before *other*.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2)).lt((1, 2, 3))
            True
            >>> Iter((1, 2, 3)).lt((1, 2, 3))
            False
            >>> Iter((1, 2, 3)).lt((1, 3))
            True

            ```
        """
        return tls.lt(iter(self), other)

    def gt(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** is lexicographically strictly greater than *other*.

        The first differing pair of elements decides the result.

        If all compared elements are equal, the longer iterable is strictly greater than the shorter one.

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` if **self** compares strictly after *other*.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).gt((1, 2))
            True
            >>> Iter((1, 3)).gt((1, 2, 9))
            True
            >>> Iter((1, 2)).gt((1, 2, 3))
            False

            ```
        """
        return tls.gt(iter(self), other)

    def ge(self, other: Iterable[T]) -> bool:
        """Return `True` if **self** is lexicographically greater than or equal to *other*.

        Comparison is performed element by element, like Python sequence ordering.

        The first differing pair decides the result.

        If all compared elements are equal and one iterable ends first, the longer iterable is considered
        greater.

        Note:
            This consumes any `Iterator` instances involved in the comparison,
            including **self** and *other* when *other* is itself an iterator.

        Args:
            other (Iterable[T]): Another `Iterable[T]` to compare against.

        Returns:
            bool: `True` if **self** is greater than *other*, or equal to it.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).ge((1, 2))
            True
            >>> Iter((1, 2, 3)).ge((1, 2, 3))
            True
            >>> Iter((1, 2)).ge((1, 2, 3))
            False

            ```
        """
        return tls.ge(iter(self), other)

    def next(self) -> Option[T]:
        """Return the next element in the `Iterator`.

        The actual `__next__()` method must be conform to the Python `Iterator` Protocol, and is what will be actually called if you iterate over the `PyoIterator` instance.

        `PyoIterator::next` is a convenience method that wraps the result in an `Option` to handle exhaustion gracefully, for custom use cases.

        Returns:
            Option[T]: The next element in the iterator. `Some[T]`, or `NONE` if the iterator is exhausted.

        Example:
            ```python
            >>> from pyochain import Seq
            >>> it = Seq((1, 2, 3)).iter()
            >>> it.next().unwrap()
            1
            >>> it.next().unwrap()
            2

            ```
        """
        return option(next(self, None))

    def reduce(self, func: Callable[[T, T], T]) -> T:
        """Apply a function of two arguments cumulatively to the items of an iterable, from left to right.

        This effectively reduces the `Iterator` to a single value.

        If initial is present, it is placed before the items of the `Iterator` in the calculation.

        It then serves as a default when the `Iterator` is empty.

        Args:
            func (Callable[[T, T], T]): Function to apply cumulatively to the items of the iterable.

        Returns:
            T: Single value resulting from cumulative reduction.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).reduce(lambda a, b: a + b)
            6

            ```
        """
        return functools.reduce(func, self)

    def fold[B](self, init: B, func: Callable[[B, T], B]) -> B:
        """Fold every element of the `Iterator` into an accumulator by applying an operation, returning the final result.

        Args:
            init (B): Initial value for the accumulator.
            func (Callable[[B, T], B]): Function that takes the accumulator and current element,
                returning the new accumulator value.

        Returns:
            B: The final accumulated value.

        Note:
            This is similar to `reduce()` but with an initial value.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> data = (1, 2, 3)
            >>> Iter(data).fold(0, lambda acc, x: acc + x)
            6
            >>> Iter(data).fold(10, lambda acc, x: acc + x)
            16
            >>> Iter(("a", "b", "c")).fold("", lambda acc, x: acc + x)
            'abc'

            ```
        """
        return functools.reduce(func, self, init)

    @overload
    def fold_star[**P, B](
        self: PyoIterator[tuple[Any]],  # pyright: ignore[reportExplicitAny]
        init: B,
        func: Callable[[Any], B],  # pyright: ignore[reportExplicitAny]
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, **P, B](
        self: PyoIterator[tuple[T1, T2]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, **P, B](
        self: PyoIterator[tuple[T1, T2, T3]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, T6, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, T6, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, T6, T7, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, T6, T7, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, T6, T7, T8, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, T6, T7, T8, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, T6, T7, T8, T9, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    @overload
    def fold_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, **P, B](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        init: B,
        func: Callable[Concatenate[B, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, P], B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B: ...
    def fold_star[U: Iterable[Any], **P, B](
        self: PyoIterator[U],
        init: B,
        func: Callable[..., B],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> B:
        """Fold every element of the `Iterator` into an accumulator by applying an operation, returning the final result.

        Use this when the items of the `Iterator` are themselves iterables (e.g., tuples), and you want to unpack them as arguments to the folding function.

        Args:
            init (B): Initial value for the accumulator.
            func (Callable[..., B]): Function that takes the accumulator and current element, returning the new accumulator value.
            *args (P.args): Additional positional arguments to pass to **func**.
            **kwargs (P.kwargs): Additional keyword arguments to pass to **func**.

        Returns:
            B: The final accumulated value.

        Note:
            This is similar to `Iter::reduce` but with an initial value.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> data = ((1, 2), (3, 4))
            >>> Iter(data).fold_star(0, lambda acc, x, y: acc + x + y)
            10
            >>> data = (("a", "b"), ("c", "d"))
            >>> Iter(data).fold_star("", lambda acc, x, y: acc + x + y)
            'abcd'

            ```
        """

        def _reducer(acc: B, item: U) -> B:
            return func(acc, *item, *args, **kwargs)

        return functools.reduce(_reducer, self, init)

    def find(self, predicate: Callable[[T], bool]) -> Option[T]:
        """Searches for an element of an iterator that satisfies a `predicate`.

        Takes a closure that returns true or false as `predicate`, and applies it to each element of the iterator.

        Args:
            predicate (Callable[[T], bool]): Function to evaluate each item.

        Returns:
            Option[T]: The first element satisfying the predicate. `Some(value)` if found, `NONE` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter, Range
            >>> def gt_five(x: int) -> bool:
            ...     return x > 5
            >>>
            >>> def gt_nine(x: int) -> bool:
            ...     return x > 9
            >>> data = Range(0, 10)
            >>> data.iter().find(predicate=gt_five)
            Some(6)
            >>> data.iter().find(predicate=gt_nine).unwrap_or("missing")
            'missing'

            ```
        """
        return option(next(filter(predicate, self), None))

    def try_find[E](
        self, predicate: Callable[[T], Result[bool, E]]
    ) -> Result[Option[T], E]:
        """Applies a function returning `Result[bool, E]` to find first matching element.

        Short-circuits: stops at the first successful `True` or on the first error.

        Args:
            predicate (Callable[[T], Result[bool, E]]): Function returning a `Result[bool, E]`.

        Returns:
            Result[Option[T], E]: The first matching element, or the first error.

        Example:
            ```python
            >>> from pyochain import Ok, Result, Err, Range
            >>> def is_even(x: int) -> Result[bool, str]:
            ...     return Ok(x % 2 == 0) if x >= 0 else Err("negative number")
            >>>
            >>> Range(1, 6).iter().try_find(is_even)
            Ok(Some(2))

            ```
        """
        return tls.try_find(iter(self), predicate)

    def try_fold[B, E](
        self, init: B, func: Callable[[B, T], Result[B, E]]
    ) -> Result[B, E]:
        """Folds every element into an accumulator, short-circuiting on error.

        Applies **func** cumulatively to items and the accumulator.

        If **func** returns an error, stops and returns that error.

        Args:
            init (B): Initial accumulator value.
            func (Callable[[B, T], Result[B, E]]): Function that takes the accumulator and element, returns a `Result[B, E]`.

        Returns:
            Result[B, E]: Final accumulator or the first error.

        Example:
            ```python
            >>> from pyochain import Iter, Ok, Err, Result
            >>> def checked_add(acc: int, x: int) -> Result[int, str]:
            ...     new_val = acc + x
            ...     if new_val > 100:
            ...         return Err("overflow")
            ...     return Ok(new_val)
            >>>
            >>> Iter((1, 2, 3)).try_fold(0, checked_add)
            Ok(6)
            >>> Iter([50, 40, 20]).try_fold(0, checked_add)
            Err('overflow')
            >>> Iter(()).try_fold(0, checked_add)
            Ok(0)

            ```
        """
        return tls.try_fold(iter(self), init, func)

    def try_reduce[E](
        self, func: Callable[[T, T], Result[T, E]]
    ) -> Result[Option[T], E]:
        """Reduces elements to a single one, short-circuiting on error.

        Uses the first element as the initial accumulator. If **func** returns an error, stops immediately.

        Args:
            func (Callable[[T, T], Result[T, E]]): Function that reduces two items, returns a `Result[T, E]`.

        Returns:
            Result[Option[T], E]: Final accumulated value or the first error. Returns `Ok(NONE)` for empty iterable.

        Example:
            ```python
            >>> from pyochain import Iter, Ok, Err, Result
            >>> def checked_add(x: int, y: int) -> Result[int, str]:
            ...     if x + y > 100:
            ...         return Err("overflow")
            ...     return Ok(x + y)
            >>>
            >>> Iter((1, 2, 3)).try_reduce(checked_add)
            Ok(Some(6))
            >>> Iter([50, 60]).try_reduce(checked_add)
            Err('overflow')
            >>> Iter(()).try_reduce(checked_add)
            Ok(NONE)

            ```
        """
        return tls.try_reduce(iter(self), func)

    def is_sorted[U: SupportsComparison[Any]](
        self: PyoIterator[U], *, reverse: bool = False, strict: bool = False
    ) -> bool:
        """Returns `True` if the items of the `Iterator` are in sorted order.

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

        The function returns `False` after encountering the first out-of-order item.

        If there are no out-of-order items, the `Iterator` is exhausted.

        Credits to **more-itertools** for the implementation.

        See Also:
            [`PyoIterator::is_sorted_by`][is_sorted_by] if your elements do not support comparison operations directly, or you want to sort based on a specific attribute or transformation.

        Args:
            reverse (bool): Whether to check for descending order.
            strict (bool): Whether to enforce strict sorting (no equal elements).

        Returns:
            bool: `True` if items are sorted according to the criteria, `False` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3, 4, 5)).is_sorted()
            True

            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            >>> Iter([1, 2, 2]).is_sorted()
            True
            >>> Iter([1, 2, 2]).is_sorted(strict=True)
            False

            ```
        """
        return tls.is_sorted(iter(self), reverse=reverse, strict=strict)

    def is_sorted_by(
        self,
        key: Callable[[T], SupportsComparison[Any]],  # pyright: ignore[reportExplicitAny]
        *,
        reverse: bool = False,
        strict: bool = False,
    ) -> bool:
        """Returns `True` if the items of the `Iterator` are in sorted order according to the key function.

        The function returns `False` after encountering the first out-of-order item.

        If there are no out-of-order items, the `Iterator` is exhausted.

        Credits to **more-itertools** for the implementation.

        Args:
            key (Callable[[T], SupportsComparison[Any]]): Function to extract a comparison key from each element.
            reverse (bool): Whether to check for descending order.
            strict (bool): Whether to enforce strict sorting (no equal elements).

        Returns:
            bool: `True` if items are sorted according to the criteria, `False` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter(["1", "2", "3", "4", "5"]).is_sorted_by(int)
            True
            >>> Iter(["5", "4", "3", "1", "2"]).is_sorted_by(int, reverse=True)
            False

            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            >>> Iter(["1", "2", "2"]).is_sorted_by(int)
            True
            >>> Iter(["1", "2", "2"]).is_sorted_by(key=int, strict=True)
            False

            ```
        """
        return tls.is_sorted_by(iter(self), key, reverse=reverse, strict=strict)

    def all_equal[U](self, key: Callable[[T], U] | None = None) -> bool:
        """Return `True` if all items of the `Iterator` are equal.

        A function that accepts a single argument and returns a transformed version of each input item can be specified with **key**.

        Credits to **more-itertools** for the implementation.

        Args:
            key (Callable[[T], U] | None): Function to transform items before comparison.

        Returns:
            bool: `True` if all items are equal, `False` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter("AaaA").all_equal(key=str.casefold)
            True
            >>> Iter((1, 2, 3)).all_equal(key=lambda x: x < 10)
            True

            ```
        """
        iterator = itertools.groupby(iter(self), key)
        for _first in iterator:
            for _second in iterator:
                return False
            return True
        return True

    def all_unique[U](self) -> bool:
        """Returns `True` if all the elements of the `Iterator` are unique.

        The function returns as soon as the first non-unique element is encountered.

        Elements are assumed to be hashable.

        If you need to check uniqueness based on a custom key function, use `PyoIterable::all_unique_by` instead.

        Tip:
            If you already have an existing `Collection`, you can alternatively check uniqueness by comparing the length of the collection to the length of a set created from it.

            On a "worst" case scenario (all elements are unique), this can be a bit faster on large (100k + items) collections, by around 1.15x (i.e 15% faster).

            Or on very small (10 items or less), where the overhead of creating the `Iterator` makes it 2x slower than simply creating the set.

            Altough, at this point, the operation is so fast that the difference is negligible, unless you are doing it in a hot loop.

            All things considered, `all_unique` early-exits on first duplicate can make it orders of magnitude faster, when your probability of duplicates is anything but very low.

        Returns:
            bool: `True` if all elements are unique, `False` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter, Seq, Set
            >>> Iter("ABCB").all_unique()
            False
            >>> Iter("ABCb").all_unique()
            True
            >>> # Alternative way to check uniqueness by comparing lengths:
            >>> collection = Seq((1, 2, 3, 3))
            >>> collection.len() == collection.into(Set).len()
            False

            ```
        """
        return tls.all_unique(iter(self))

    def arg_max(self) -> int:
        """Index of the first occurrence of a maximum value in the `Iterator`.

        Credits to more-itertools for the implementation.

        Returns:
            int: The index of the maximum value.

        Example:
            Basic usage:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter("abcdefghabcd").arg_max()
            7
            >>> Iter((0, 1, 2, 3, 3, 2, 1, 0)).arg_max()
            3

            ```
            Identify the best machine learning model:
            ```python
            >>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
            >>> accuracy = Seq((68, 61, 84, 72))
            >>> # Most accurate model
            >>> models.get(accuracy.iter().arg_max()).unwrap()
            'knn'
            >>> # Best accuracy
            >>> accuracy.iter().max()
            84

            ```
        """
        return max(enumerate(iter(self)), key=itemgetter(1))[0]

    def arg_max_by[U](self, key: Callable[[T], U]) -> int:
        """Index of the first occurrence of a maximum value in the `Iterator` based on a *key* function.

        The *key* function must accept a single argument and return a transformed, comparable version of each input item.

        Credits to more-itertools for the implementation.

        Args:
            key (Callable[[T], U]): Function to determine the value for comparison.

        Returns:
            int: The index of the maximum value.

        Example:
            Basic usage:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter(("a", "bbb", "cc")).arg_max_by(len)
            1
            >>> Iter(("Alice", "bob", "charlie")).arg_max_by(str.lower)
            2

            ```
            Identify the best machine learning model:
            ```python
            >>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
            >>> accuracy = Seq(("68", "61", "84", "72"))
            >>> # Most accurate model
            >>> models.get(accuracy.iter().arg_max_by(int)).unwrap()
            'knn'
            >>> # Best accuracy
            >>> accuracy.iter().max_by(int)
            '84'

            ```
        """
        return max(enumerate(map(key, iter(self))), key=itemgetter(1))[0]

    def arg_min(self) -> int:
        """Index of the first occurrence of a minimum value in the `Iterator`.

        Credits to more-itertools for the implementation.

        Returns:
            int: The index of the minimum value.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> # Example 1: Basic usage
            >>> Iter("efghabcdijkl").arg_min()
            4
            >>> Iter((3, 2, 1, 0, 4, 2, 1, 0)).arg_min()
            3

            ```
        """
        return min(enumerate(iter(self)), key=itemgetter(1))[0]

    def arg_min_by[U](self, key: Callable[[T], U]) -> int:
        """Index of the first occurrence of a minimum value in the `Iterator` based on a *key* function.

        The *key* function must accept a single argument and return a transformed, comparable version of each input item.

        Credits to more-itertools for the implementation.

        Args:
            key (Callable[[T], U]): Function to determine the value for comparison.

        Returns:
            int: The index of the minimum value.

        Example:
            Basic usage:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter(("aaa", "b", "cc")).arg_min_by(len)
            1
            >>> Iter(("Alice", "bob", "Charlie")).arg_min_by(str.lower)
            0

            ```
            Identify the best machine learning model:
            ```python
            >>> def cost(x: int) -> float:
            ...     "Days for a wound to heal given a subject's age."
            ...     return x**2 - 20 * x + 150
            >>>
            >>> labels = Seq(("homer", "marge", "bart", "lisa", "maggie"))
            >>> ages = Seq((35, 30, 10, 9, 1))
            >>> # Fastest healing family member
            >>> labels.get(ages.iter().arg_min_by(cost)).unwrap()
            'bart'
            >>> # Age with fastest healing
            >>> ages.iter().min_by(key=cost)
            10

            ```
        """
        return min(enumerate(map(key, iter(self))), key=itemgetter(1))[0]

    def for_each[**P](
        self,
        func: Callable[Concatenate[T, P], Any],  # pyright: ignore[reportExplicitAny]
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None:
        """Consume the `Iterator` by applying a function to each element in the `Iterable`.

        Is a terminal operation, and is useful for functions that have side effects,
        or when you want to force evaluation of a lazy iterable.

        Args:
            func (Callable[Concatenate[T, P], Any]): Function to apply to each element.
            *args (P.args): Positional arguments for the function.
            **kwargs (P.kwargs): Keyword arguments for the function.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).for_each(lambda x: print(x + 1))
            2
            3
            4

            ```
        """
        tls.for_each(iter(self), func, *args, **kwargs)

    @overload
    def for_each_star[T1, T2, **P, R](
        self: PyoIterator[tuple[T1, T2]],
        func: Callable[Concatenate[T1, T2, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, **P, R](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[Concatenate[T1, T2, T3, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4]],
        func: Callable[Concatenate[T1, T2, T3, T4, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, T6, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, T6, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, T6, T7, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, T6, T7, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, T6, T7, T8, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, T6, T7, T8, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, T6, T7, T8, T9, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    @overload
    def for_each_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, **P, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[Concatenate[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None: ...
    def for_each_star[U: tuple[Any, ...], **P, R](
        self: PyoIterator[U],
        func: Callable[..., R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None:
        """Consume the `Iterator` by applying a function to each unpacked item in the `Iterable` element.

        Is a terminal operation, and is useful for functions that have side effects,
        or when you want to force evaluation of a lazy iterable.

        Each item yielded by the `Iterator` is expected to be an `Iterable` itself (e.g., a tuple or list),
        and its elements are unpacked as arguments to the provided function.

        This is often used after methods like `zip()` or `enumerate()` that yield tuples.

        Args:
            func (Callable[..., R]): Function to apply to each unpacked element.
            *args (P.args): Positional arguments for the function.
            **kwargs (P.kwargs): Keyword arguments for the function.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter(((1, 2), (3, 4))).for_each_star(lambda x, y: print(x + y))
            3
            7

            ```
        """
        tls.for_each_star(iter(self), func, *args, **kwargs)

    def try_for_each[E](self, f: Callable[[T], Result[Any, E]]) -> Result[tuple[()], E]:  # pyright: ignore[reportExplicitAny]
        """Applies a fallible function to each item in the `Iterator`, stopping at the first error and returning that error.

        This can also be thought of as the fallible form of `.for_each()`.

        Args:
            f (Callable[[T], Result[Any, E]]): A function that takes an item of type `T` and returns a `Result`.

        Returns:
            Result[tuple[()], E]: Returns `Ok(())` if all applications of **f** were successful (i.e., returned `Ok`), or the first error `E` encountered.

        Example:
            ```python
            >>> from pyochain import Iter, Result, Ok, Err
            >>> def validate_positive(n: int) -> Result[tuple[()], str]:
            ...     if n > 0:
            ...         return Ok("success")
            ...     return Err(f"Value {n} is not positive")
            >>>
            >>> Iter((1, 2, 3, 4, 5)).try_for_each(validate_positive)
            Ok(())
            >>> # Short-circuit on first error:
            >>> Iter((1, 2, -1, 4)).try_for_each(validate_positive)
            Err('Value -1 is not positive')

            ```
        """
        return tls.try_for_each(iter(self), f)

    def collect[R: Collection[Any]](self, collector: Callable[[Iterator[T]], R]) -> R:
        """Transforms the `Iterator` into a collection.

        The most basic pattern in which `collect()` is used is to turn one collection into another.

        You take a collection, call `iter()` on it, do a bunch of transformations, and then `collect()` at the end.

        You specify the target `Collection` type by providing a **collector** function or type.

        This can be any `Callable` that takes an `Iterator[T]` and returns a `Collection[T]` of those types.

        This is equivalent to `Pipeable::into` at runtime, but with a few differences:

            - A narrower constraint (`Collection[Any]`) to specify the intent
            - Better performance (no args/kwargs unpacking).

        If you need to pass additional arguments, you can use [`Pipeable::into`][Pipeable.into] instead.

        Note:
            `Iter::collect` is overriden to provide `Seq` as the default **collector**.

        Args:
            collector (Callable[[Iterator[T]], R]): Function|type that defines the target collection. `R` is constrained to a `Collection`.

        Returns:
            R: A materialized `Collection` containing the collected elements.

        Example:
            ```python
            >>> from pyochain import Iter, Range, Vec, Dict
            >>> data = Range(0, 5)
            >>> data.iter().collect(list)
            [0, 1, 2, 3, 4]
            >>> data.iter().collect(Vec)
            Vec(0, 1, 2, 3, 4)
            >>> data.iter().map(str).enumerate().collect(Dict)
            Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')

            ```
            Sometimes type checkers can't infer the type of the collector, in which case you can use an explicit type annotation to help them out.

            In the example below, without the annotation in `collect()`,

            BasedPyright infer `data` as `Seq[Result[int, Any] | Result[Any, int]]` because of the conditional expression in the `map()`, which is not very useful.
            ```python
            >>> from pyochain import Range, Seq, Ok, Err, Result
            >>> data = (
            ...     Range(0, 5)
            ...     .iter()
            ...     .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
            ...     .collect(Seq[Result[int, int]])
            ... )
            >>> data
            Seq(Ok(0), Err(1), Ok(2), Err(3), Ok(4))

            ```
            Strictly speaking, this is equivalent to annotating the variable at the beginning, but some may prefer this style to keep the type information close to the actual collection operation.

            This notably avoid repetition if you collect anything else than the default `Seq` type.
        """
        return collector(iter(self))

    @overload
    def collect_into(self, collection: Vec[T]) -> Vec[T]: ...
    @overload
    def collect_into(
        self, collection: PyoMutableSequence[T]
    ) -> PyoMutableSequence[T]: ...
    @overload
    def collect_into(self, collection: list[T]) -> list[T]: ...
    def collect_into(self, collection: MutableSequence[T]) -> MutableSequence[T]:
        """Collects all the items from the `Iterator` into a `MutableSequence`.

        The `MutableSequence` is then returned, so the call chain can be continued.

        This is useful when you already have a `MutableSequence` and want to add the `Iterator` items to it.

        This method is a convenience method to call `MutableSequence.extend()`, but instead of being called on a `MutableSequence`, it's called on an `Iterator`.

        Args:
            collection (MutableSequence[T]): A mutable collection to collect items into.

        Returns:
            MutableSequence[T]: The same mutable collection passed as argument, now containing the collected items.

        Example:
            Basic usage:
            ```python
            >>> from pyochain import Seq, Iter, Vec
            >>> a = Seq((1, 2, 3))
            >>> vec = Vec.from_ref([0, 1])
            >>> a.iter().map(lambda x: x * 2).collect_into(vec)
            Vec(0, 1, 2, 4, 6)
            >>> a.iter().map(lambda x: x * 10).collect_into(vec)
            Vec(0, 1, 2, 4, 6, 10, 20, 30)

            ```
            The returned mutable sequence can be used to continue the call chain:
            ```python
            >>> from pyochain import Seq, Vec
            >>> a = Seq((1, 2, 3))
            >>> vec = Vec(())
            >>> a.iter().collect_into(vec).len() == vec.len()
            True
            >>> a.iter().collect_into(vec).len() == vec.len()
            True

            ```
        """
        collection.extend(iter(self))
        return collection

    @overload
    def try_collect[U](self: PyoIterator[Option[U]]) -> Option[Vec[U]]: ...
    @overload
    def try_collect[U, E](self: PyoIterator[Result[U, E]]) -> Option[Vec[U]]: ...
    def try_collect[U](
        self: PyoIterator[Option[U]] | PyoIterator[Result[U, Any]],  # pyright: ignore[reportExplicitAny]
    ) -> Option[Vec[U]]:
        """Fallibly transforms **self** into a `Vec`, short circuiting if a failure is encountered.

        `try_collect()` is a variation of `collect()` that allows fallible conversions during collection.

        Its main use case is simplifying conversions from iterators yielding `Option[T]` or `Result[T, E]` into `Option[Vec[T]]`.

        Also, if a failure is encountered during `try_collect()`, the `Iter` is still valid and may continue to be used, in which case it will continue iterating starting after the element that triggered the failure.

        See the last example below for an example of how this works.

        Note:
            This method return `Vec[U]` instead of being customizable, because the underlying data structure must be mutable in order to build up the collection.

        Returns:
            Option[Vec[U]]: `Some[Vec[U]]` if all elements were successfully collected, or `NONE` if a failure was encountered.

        Example:
            ```python
            >>> from pyochain import Iter, Some, Ok, Err, NONE, Vec
            >>> # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
            >>> Iter((Some(1), Some(2), Some(3))).try_collect()
            Some(Vec(1, 2, 3))
            >>> # Failing to collect in the same way:
            >>> Iter((Some(1), Some(2), NONE, Some(3))).try_collect()
            NONE
            >>> # A similar example, but with Result:
            >>> Iter((Ok(1), Ok(2), Ok(3))).try_collect()
            Some(Vec(1, 2, 3))
            >>> Iter((Ok(1), Err("error"), Ok(3))).try_collect()
            NONE
            >>> def external_fn(x: int) -> Option[int]:
            ...     if x % 2 == 0:
            ...         return Some(x)
            ...     return NONE
            >>>
            >>> Iter((1, 2, 3, 4)).map(external_fn).try_collect()
            NONE
            >>> # Demonstrating that the iterator remains usable after a failure:
            >>> it = Iter((Some(1), NONE, Some(3), Some(4)))
            >>> it.try_collect()
            NONE
            >>> it.try_collect()
            Some(Vec(3, 4))

            ```
        """
        from .._vec import Vec

        return tls.try_collect(iter(self)).map(Vec.from_ref)

    def sort[U: SupportsRichComparison[Any]](
        self: PyoIterator[U], *, reverse: bool = False
    ) -> Vec[U]:
        """Sort the elements of the `Iterator`.

        The elements must support rich comparison operations (i.e., they must implement the necessary comparison dunder methods).

        Note:
            This method must consume the entire `Iterator` to perform the sort.

            The result is a new `Vec` over the sorted sequence.

        Args:
            reverse (bool): Whether to sort in descending order.

        Returns:
            Vec[U]: A `Vec` with elements sorted.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((3, 1, 2)).sort()
            Vec(1, 2, 3)

            ```
        """
        from .._vec import Vec

        return Vec.from_ref(sorted(iter(self), reverse=reverse))

    def sort_by(
        self,
        key: Callable[[T], SupportsRichComparison[Any]],  # pyright: ignore[reportExplicitAny]
        *,
        reverse: bool = False,
    ) -> Vec[T]:
        """Sort the elements of the sequence transformed by the key function.

        Note:
            This method must consume the entire `Iterator` to perform the sort.

            The result is a new `Vec` over the sorted sequence.

        Args:
            key (Callable[[T], SupportsRichComparison[Any]]): Function to extract a comparison key from each element.
            reverse (bool): Whether to sort in descending order.

        Returns:
            Vec[T]: A `Vec` with elements sorted.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> str_numbers = ("3", "1", "2")
            >>> Iter(str_numbers).sort_by(int)
            Vec('1', '2', '3')
            >>> Iter(str_numbers).sort_by(int, reverse=True)
            Vec('3', '2', '1')
            >>> from dataclasses import dataclass
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            >>>
            >>> peoples = (
            ...     Person("Alice", 30),
            ...     Person("Bob", 25),
            ...     Person("Charlie", 35),
            ... )
            >>> sorted_names = (
            ...     Iter(peoples)
            ...     .sort_by(lambda x: x.age)
            ...     .iter()
            ...     .map(lambda x: x.name)
            ...     .collect()
            ... )
            >>> sorted_names
            Seq('Bob', 'Alice', 'Charlie')

            ```
        """
        from .._vec import Vec

        return Vec.from_ref(sorted(iter(self), reverse=reverse, key=key))

    def tail(self, n: int) -> Deque[T]:
        """Return a `Deque` of the last **n** elements of the `Iterator`.

        Args:
            n (int): Number of elements to return.

        Returns:
            Deque[T]: A `Deque` containing the last **n** elements.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).tail(2)
            Deque([2, 3], maxlen=2)

            ```
        """
        from collections import deque

        from ..collections import Deque

        # TODO: we should move this to Rust and make it fully lazy.
        return Deque.from_ref(deque(iter(self), n))

    def partition(self, predicate: Callable[[T], bool]) -> tuple[Vec[T], Vec[T]]:
        """Consumes the `Iterator`, creating two `Vec` from it.

        The predicate passed to `partition()` can return true, or false.

        `partition` returns a pair, all of the elements for which it returned `True`, and all of the elements for which it returned `False`.

        Args:
            predicate (Callable[[T], bool]): Function to determine partition boundaries.

        Returns:
            tuple[Vec[T], Vec[T]]: The resulting pair of collections

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3, 4, 5)).partition(lambda x: x % 2 == 0)
            (Vec(2, 4), Vec(1, 3, 5))

            ```
        """
        from .._vec import Vec

        first, second = tls.partition(iter(self), predicate)
        return Vec.from_ref(first), Vec.from_ref(second)

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

        This is equivalent to the built-in `str.join()` method, but as a method on the `Iterator` itself.

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

        Returns:
            str: The joined string.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter(("a", "b", "c")).join("-")
            'a-b-c'

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

    @overload
    def sum(self: PyoIterator[bool], start: int = 0) -> int: ...
    @overload
    def sum(self: PyoIterator[LiteralInteger], start: int = 0) -> int: ...
    @overload
    def sum[T1: SupportsSumWithNoDefaultGiven](
        self: PyoIterator[T1],
    ) -> T1 | Literal[0]: ...
    @overload
    def sum[A1: SupportsAnyAdd, A2: SupportsAnyAdd](
        self: PyoIterator[A1], start: A2
    ) -> A1 | A2: ...
    def sum[T1: SupportsSumWithNoDefaultGiven, A1: SupportsAnyAdd, A2: SupportsAnyAdd](
        self: PyoIterator[bool | LiteralInteger] | PyoIterator[T1] | PyoIterator[A1],
        start: int | T1 | A2 = 0,
    ) -> int | T1 | A1 | A2:
        """Return the sum of the `Iterator`.

        If the `Iterator` is empty (i.e., yields no elements), return the value of `start` (which defaults to `0`).

        Args:
            start (int | T1 | A2): The value to return if the `Iterator` is empty.

        Returns:
            int | T1 | A1 | A2: The sum of all elements.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter((1, 2, 3)).sum()
            6
            >>> Iter(()).sum()
            0
            >>> Iter(()).sum(10)
            10

            ```
        """
        return sum(iter(self), start)

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

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

        For comparing elements using a custom **key** function, use [`min_by`][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
            >>> from pyochain import Iter
            >>> Iter((3, 1, 2)).min()
            1

            ```
        """
        return min(iter(self))

    def min_by[U: SupportsRichComparison[Any]](self, key: Callable[[T], U]) -> T:
        """Return the minimum element of the `Iterator` 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
            >>> from pyochain import Seq
            >>> from dataclasses import dataclass
            >>>
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            ...     is_student: bool
            ...
            ...     def get_discount(self) -> float:
            ...         return 0.1 if self.is_student else 0.0
            >>>
            >>> alice = Person("Alice", 30, False)
            >>> bob = Person("Bob", 22, True)
            >>> charlie = Person("Charlie", 25, False)
            >>> persons = Seq((alice, bob, charlie))
            >>>
            >>> persons.iter().min_by(lambda p: p.age).name
            'Bob'
            >>> persons.iter().min_by(lambda p: p.name).name
            'Alice'
            >>> persons.iter().min_by(Person.get_discount).name
            'Alice'

            ```
        """
        return min(iter(self), key=key)

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

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

        For comparing elements using a custom **key** function, use [`max_by`][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
            >>> from pyochain import Iter
            >>> Iter((3, 1, 2)).max()
            3

            ```
        """
        return max(iter(self))

    def max_by[U: SupportsRichComparison[Any]](self, key: Callable[[T], U]) -> T:
        """Return the maximum element of the `Iterator` 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
            >>> from pyochain import Seq
            >>> from dataclasses import dataclass
            >>>
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            ...     is_student: bool
            ...
            ...     def get_discount(self) -> float:
            ...         return 0.1 if self.is_student else 0.0
            >>>
            >>> alice = Person("Alice", 30, False)
            >>> bob = Person("Bob", 22, True)
            >>> charlie = Person("Charlie", 25, False)
            >>> persons = Seq((alice, bob, charlie))
            >>>
            >>> persons.iter().max_by(lambda p: p.age).name
            'Alice'
            >>> persons.iter().max_by(lambda p: p.name).name
            'Charlie'
            >>> persons.iter().max_by(Person.get_discount).name
            'Bob'

            ```
        """
        return max(iter(self), key=key)

    def unpack_into[**P, R](
        self,
        func: Callable[Concatenate[T, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> R:
        """Unpack the `Iterator` in the provided *func*, and return the result.

        This is similar to `Pipeable::into`, but instead of passing `Self`, we pass the elements inside `Self`.

        This avoids you to do `iterator.into(lambda x: (*x))`, improving performance and readability.

        Note:
            This method will consume the `Iterator`.

        Args:
            func (Callable[Concatenate[T, P], R]): Function to call with the unpacked elements of the `Iterator`.
            *args (P.args): Additional positional arguments to pass to *func*
            **kwargs (P.kwargs): Additional keyword arguments to pass to *func*

        Returns:
            R: The result of calling *func* with the unpacked elements of the `Iterator` and any additional arguments.

        Example:
            ```python
            >>> from pyochain import Seq

            >>> data = Seq((1, 2, 3))
            >>> def foo(*a: int, x: str) -> str:
            ...     return x + str(sum(a))
            >>> data.iter().unpack_into(foo, x="Result: ")
            'Result: 6'
            >>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
            >>> data.iter().unpack_into(lambda a, b, c: a + b + c)
            6

            ```
        """
        return func(*iter(self), *args, **kwargs)

    def all_unique_by[U](self, key: Callable[[T], U]) -> bool:
        """Returns True if all the elements of **self** transformed by **key** are unique.

        The function returns as soon as the first non-unique element is encountered.

        Credits to **more-itertools** for the implementation.

        Args:
            key (Callable[[T], U]): Function to transform items before comparison.

        Returns:
            bool: `True` if all elements are unique, `False` otherwise.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter("ABCb").all_unique()
            True
            >>> Iter("ABCb").all_unique_by(str.lower)
            False

            ```
        """
        return tls.all_unique_by(iter(self), key)

    def take_while(self, predicate: Callable[[T], bool]) -> Self:
        """Take items while predicate holds.

        Args:
            predicate (Callable[[T], bool]): Function to evaluate each item.

        Returns:
            Self: An `Iterator` of the items taken while the predicate is true.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 0)).take_while(lambda x: x > 0).collect()
            Seq(1, 2)

            ```
        """
        return self._from_iterable(itertools.takewhile(predicate, iter(self)))

    def skip_while(self, predicate: Callable[[T], bool]) -> Self:
        """Drop items while predicate holds.

        Args:
            predicate (Callable[[T], bool]): Function to evaluate each item.

        Returns:
            Self: An `Iterator` of the items after skipping those for which the predicate is true.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 0)).skip_while(lambda x: x > 0).collect()
            Seq(0,)

            ```
        """
        return self._from_iterable(itertools.dropwhile(predicate, iter(self)))

    def compress(self, *selectors: bool) -> Self:
        """Filter elements using a boolean selector iterable.

        Args:
            *selectors (bool): Boolean values indicating which elements to keep.

        Returns:
            Self: An `Iterator` of the items selected by the boolean selectors.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect()
            Seq('A', 'C', 'E', 'F')

            ```
        """
        return self._from_iterable(itertools.compress(iter(self), selectors))

    def unique(self) -> Self:
        """Return only unique elements of the iterable.

        Returns:
            Self: An `Iterator` of the unique items.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).unique().collect()
            Seq(1, 2, 3)
            >>> Iter([1, 2, 1, 3]).unique().collect()
            Seq(1, 2, 3)

            ```
        """
        return self._from_iterable(tls.UniqueIdentity(iter(self)))

    def unique_by(self, key: Callable[[T], Any]) -> Self:  # pyright: ignore[reportExplicitAny]
        """Return only unique elements of the iterable.

        Args:
            key (Callable[[T], Any]): Function to transform items before comparison.

        Returns:
            Self: An `Iterator` of the unique items.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter(["cat", "mouse", "dog", "hen"]).unique_by(key=len).collect()
            Seq('cat', 'mouse')

            ```
        """
        return self._from_iterable(tls.UniqueKey(iter(self), key=key))

    def take(self, n: int) -> Self:
        """Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner.

        `Iter.take(n)` yields elements until n elements are yielded or the end of the iterator is reached (whichever happens first).

        The returned iterator is either:

        - A prefix of length n if the original iterator contains at least n elements
        - All of the (fewer than n) elements of the original iterator if it contains fewer than n elements.

        Args:
            n (int): Number of elements to take.

        Returns:
            Self: An `Iterator` of the first n items.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> data = (1, 2, 3)
            >>> Iter(data).take(2).collect()
            Seq(1, 2)
            >>> Iter(data).take(5).collect()
            Seq(1, 2, 3)

            ```
        """
        return self._from_iterable(itertools.islice(iter(self), n))

    def skip(self, n: int) -> Self:
        """Create an `Iterator` that skips the first n elements.

        skip(**n**) skips elements until n elements are skipped or the end of the `Iterator` is reached (whichever happens first).

        After that, all the remaining elements are yielded.

        In particular, if the original `Iterator` is too short, then the returned `Iterator` is empty.

        If **n** is negative or zero, the original `Iterator` is returned unchanged.

        Args:
            n (int): Number of elements to skip.

        Returns:
            Self: An `Iterator` of the remaining elements.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).skip(1).collect()
            Seq(2, 3)
            >>> Iter((1, 2, 3)).skip(5).collect()
            Seq()
            >>> Iter((1, 2, 3)).skip(0).collect()
            Seq(1, 2, 3)

            ```
        """
        return self._from_iterable(itertools.islice(iter(self), n, None))

    def step_by(self, step: int) -> Self:
        """Creates an `Iterator` starting at the same point, but stepping by the given **step** at each iteration.

        Note:
            The first element of the iterator will always be returned, regardless of the **step** given.

        Args:
            step (int): Step size for selecting items.

        Returns:
            Self: An `Iterator` of every nth item.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter([0, 1, 2, 3, 4, 5]).step_by(2).collect()
            Seq(0, 2, 4)

            ```
        """
        return self._from_iterable(itertools.islice(iter(self), 0, None, step))

    def slice(
        self,
        start: int | None = None,
        stop: int | None = None,
        step: int | None = None,
    ) -> Self:
        """Return a slice of the `Iterator`.

        Args:
            start (int | None): Starting index of the slice.
            stop (int | None): Ending index of the slice.
            step (int | None): Step size for the slice.

        Returns:
            Self: An `Iterator` of the sliced items.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> data = (1, 2, 3, 4, 5)
            >>> Iter(data).slice(1, 4).collect()
            Seq(2, 3, 4)
            >>> Iter(data).slice(step=2).collect()
            Seq(1, 3, 5)

            ```
        """
        return self._from_iterable(itertools.islice(iter(self), start, stop, step))

    def cycle(self) -> Self:
        """Repeat the `Iterator` indefinitely.

        Warning:
            This creates an infinite `Iterator`.

            Be sure to use [`Iter::take`][take] or [`Iter::slice`][slice] to limit the number of items taken.

        See Also:
            [`Iter::repeat`][repeat] to repeat *self* as elements (`Iter[Self]`).

        Returns:
            Self: A new `Iterator` that cycles through the elements indefinitely.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2)).cycle().take(5).collect()
            Seq(1, 2, 1, 2, 1)

            ```
        """
        return self._from_iterable(itertools.cycle(iter(self)))

    def insert(self, value: T) -> Self:
        """Prepend the *value* to the `Iterator`.

        Note:
            This can be considered the equivalent as `list.append()`, but for a lazy `Iterator`.

            However, append add the value at the **end**, while insert add it at the **beginning**.

        See Also:
            [`Iter::chain`][chain] to add multiple elements at the end of the `Iterator`.

        Args:
            value (T): The value to prepend.

        Returns:
            Self: A new Iterable wrapper with the value prepended.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((2, 3)).insert(1).collect()
            Seq(1, 2, 3)

            ```
        """
        return self._from_iterable(itertools.chain((value,), iter(self)))

    def intersperse(self, element: T) -> Self:
        """Creates a new `Iterator` which places a copy of separator between adjacent items of the original iterator.

        Args:
            element (T): The element to interpose between items.

        Returns:
            Self: A new `Iterator` with the element interposed.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> # Simple example with numbers
            >>> Iter((1, 2, 3)).intersperse(0).collect()
            Seq(1, 0, 2, 0, 3)
            >>> # Useful when chaining with other operations
            >>> Iter([10, 20, 30]).intersperse(5).sum()
            70
            >>> # Inserting separators between groups, then flattening
            >>> Iter(((1, 2), (3, 4), (5, 6))).intersperse([-1]).flatten().collect()
            Seq(1, 2, -1, 3, 4, -1, 5, 6)

            ```
        """
        return self._from_iterable(tls.Intersperse(iter(self), element))

    def chain(self, *others: Iterable[T]) -> Self:
        """Concatenate **self** with one or more `Iterables`, any of which may be infinite.

        In other words, it links **self** and **others** together, in a chain. 🔗

        An infinite `Iterable` will prevent the rest of the arguments from being included.

        This is equivalent to `list.extend()`, except it is fully lazy and works with any `Iterable`.

        See Also:
            [`Iter::insert`][insert] to add a single element at the beginning of the `Iterator`.

        Args:
            *others (Iterable[T]): Other iterables to concatenate.

        Returns:
            Self: A new `Iterator` which will first iterate over values from the original `Iterator` and then over values from the **others** `Iterable`s.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2)).chain((3, 4), [5]).collect()
            Seq(1, 2, 3, 4, 5)
            >>> Iter((1, 2)).chain(Iter.from_count(3)).take(5).collect()
            Seq(1, 2, 3, 4, 5)

            ```
        """
        return self._from_iterable(itertools.chain.from_iterable((iter(self), *others)))

    def accumulate(self, func: Callable[[T, T], T], initial: T | None = None) -> Self:
        """Return an `Iterator` of accumulated binary function results.

        In principle, `.accumulate()` is similar to `.fold()` if you provide it with the same binary function.

        However, instead of returning the final accumulated result, it returns an `Iterator` that yields the current value `T` of the accumulator for each iteration.

        In other words, the last element yielded by `.accumulate()` is what would have been returned by `.fold()` if it had been used instead.

        Args:
            func (Callable[[T, T], T]): A binary function to apply cumulatively.
            initial (T | None): Optional initial value to start the accumulation.

        Returns:
            Self: A new `Iterator` with accumulated results.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, 2, 3)).accumulate(lambda a, b: a + b, 0).collect()
            Seq(0, 1, 3, 6)
            >>> # The final accumulated result is the same as fold:
            >>> Iter((1, 2, 3)).fold(0, lambda a, b: a + b)
            6
            >>> Iter((1, 2, 3)).accumulate(lambda a, b: a * b).collect()
            Seq(1, 2, 6)

            ```
        """
        return self._from_iterable(
            itertools.accumulate(iter(self), func, initial=initial)
        )

    def peekable(self, n: int) -> tuple[Seq[T], Self]:
        """Retrieve the next **n** elements from the `Iterator`, whilst leaving the original iterator unconsumed.

        The returned tuple contains two elements:

        - A `Seq` of the next **n** elements.
        - An `Iter` that includes the peeked elements followed by the remaining elements of the original `Iterator`.

        Args:
            n (int): Number of items to peek.

        Returns:
            tuple[Seq[T], Self]: A tuple containing the peeked elements and the remaining iterator.

        See Also:
            [`Iter::cloned`][cloned] to create an independent copy of the iterator.

        Example:
            ```python
            >>> from pyochain import Iter
            >>> peeked, remaining = Iter((1, 2, 3)).peekable(2)
            >>> peeked
            Seq(1, 2)
            >>> remaining.collect()
            Seq(1, 2, 3)

            ```
        """
        from .._seq import Seq

        iterator = iter(self)
        peeked = Seq(itertools.islice(iterator, n))
        remaining = self._from_iterable(itertools.chain(peeked, iterator))
        return peeked, remaining

accumulate(func, initial=None)

Return an Iterator of accumulated binary function results.

In principle, .accumulate() is similar to .fold() if you provide it with the same binary function.

However, instead of returning the final accumulated result, it returns an Iterator that yields the current value T of the accumulator for each iteration.

In other words, the last element yielded by .accumulate() is what would have been returned by .fold() if it had been used instead.

Parameters:

Name Type Description Default
func Callable[[T, T], T]

A binary function to apply cumulatively.

required
initial T | None

Optional initial value to start the accumulation.

None

Returns:

Name Type Description
Self Self

A new Iterator with accumulated results.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).accumulate(lambda a, b: a + b, 0).collect()
Seq(0, 1, 3, 6)
>>> # The final accumulated result is the same as fold:
>>> Iter((1, 2, 3)).fold(0, lambda a, b: a + b)
6
>>> Iter((1, 2, 3)).accumulate(lambda a, b: a * b).collect()
Seq(1, 2, 6)
Source code in src/pyochain/abc/_iterator.py
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
def accumulate(self, func: Callable[[T, T], T], initial: T | None = None) -> Self:
    """Return an `Iterator` of accumulated binary function results.

    In principle, `.accumulate()` is similar to `.fold()` if you provide it with the same binary function.

    However, instead of returning the final accumulated result, it returns an `Iterator` that yields the current value `T` of the accumulator for each iteration.

    In other words, the last element yielded by `.accumulate()` is what would have been returned by `.fold()` if it had been used instead.

    Args:
        func (Callable[[T, T], T]): A binary function to apply cumulatively.
        initial (T | None): Optional initial value to start the accumulation.

    Returns:
        Self: A new `Iterator` with accumulated results.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).accumulate(lambda a, b: a + b, 0).collect()
        Seq(0, 1, 3, 6)
        >>> # The final accumulated result is the same as fold:
        >>> Iter((1, 2, 3)).fold(0, lambda a, b: a + b)
        6
        >>> Iter((1, 2, 3)).accumulate(lambda a, b: a * b).collect()
        Seq(1, 2, 6)

        ```
    """
    return self._from_iterable(
        itertools.accumulate(iter(self), func, initial=initial)
    )

all(predicate=None)

Tests if every element of the Iterator is truthy.

PyoIterator::.all can optionally take a closure that returns true or false.

It applies this closure to each element of the Iterator, and if they all return true, then so does PyoIterator::.all.

If any of them return false, it returns false.

An empty Iterator 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
>>> from pyochain import Iter
>>> Iter((1, True)).all()
True
>>> Iter(()).all()
True
>>> Iter((1, 0)).all()
False
>>> def is_even(x: int) -> bool:
...     return x % 2 == 0
>>>
>>> Iter((2, 4, 6)).all(is_even)
True
>>> Iter(("a", "", "c")).all()
False
>>> Iter((1, None, 3)).all()
False
Source code in src/pyochain/abc/_iterator.py
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
def all(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if every element of the `Iterator` is truthy.

    `PyoIterator::.all` can optionally take a closure that returns true or false.

    It applies this closure to each element of the `Iterator`, and if they all return true, then so does `PyoIterator::.all`.

    If any of them return false, it returns false.

    An empty `Iterator` 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
        >>> from pyochain import Iter
        >>> Iter((1, True)).all()
        True
        >>> Iter(()).all()
        True
        >>> Iter((1, 0)).all()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>>
        >>> Iter((2, 4, 6)).all(is_even)
        True
        >>> Iter(("a", "", "c")).all()
        False
        >>> Iter((1, None, 3)).all()
        False

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

all_equal(key=None)

Return True if all items of the Iterator are equal.

A function that accepts a single argument and returns a transformed version of each input item can be specified with key.

Credits to more-itertools for the implementation.

Parameters:

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

Function to transform items before comparison.

None

Returns:

Name Type Description
bool bool

True if all items are equal, False otherwise.

Example
>>> from pyochain import Iter
>>> Iter("AaaA").all_equal(key=str.casefold)
True
>>> Iter((1, 2, 3)).all_equal(key=lambda x: x < 10)
True
Source code in src/pyochain/abc/_iterator.py
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
def all_equal[U](self, key: Callable[[T], U] | None = None) -> bool:
    """Return `True` if all items of the `Iterator` are equal.

    A function that accepts a single argument and returns a transformed version of each input item can be specified with **key**.

    Credits to **more-itertools** for the implementation.

    Args:
        key (Callable[[T], U] | None): Function to transform items before comparison.

    Returns:
        bool: `True` if all items are equal, `False` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter("AaaA").all_equal(key=str.casefold)
        True
        >>> Iter((1, 2, 3)).all_equal(key=lambda x: x < 10)
        True

        ```
    """
    iterator = itertools.groupby(iter(self), key)
    for _first in iterator:
        for _second in iterator:
            return False
        return True
    return True

all_unique()

Returns True if all the elements of the Iterator are unique.

The function returns as soon as the first non-unique element is encountered.

Elements are assumed to be hashable.

If you need to check uniqueness based on a custom key function, use PyoIterable::all_unique_by instead.

Tip

If you already have an existing Collection, you can alternatively check uniqueness by comparing the length of the collection to the length of a set created from it.

On a "worst" case scenario (all elements are unique), this can be a bit faster on large (100k + items) collections, by around 1.15x (i.e 15% faster).

Or on very small (10 items or less), where the overhead of creating the Iterator makes it 2x slower than simply creating the set.

Altough, at this point, the operation is so fast that the difference is negligible, unless you are doing it in a hot loop.

All things considered, all_unique early-exits on first duplicate can make it orders of magnitude faster, when your probability of duplicates is anything but very low.

Returns:

Name Type Description
bool bool

True if all elements are unique, False otherwise.

Example
>>> from pyochain import Iter, Seq, Set
>>> Iter("ABCB").all_unique()
False
>>> Iter("ABCb").all_unique()
True
>>> # Alternative way to check uniqueness by comparing lengths:
>>> collection = Seq((1, 2, 3, 3))
>>> collection.len() == collection.into(Set).len()
False
Source code in src/pyochain/abc/_iterator.py
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
def all_unique[U](self) -> bool:
    """Returns `True` if all the elements of the `Iterator` are unique.

    The function returns as soon as the first non-unique element is encountered.

    Elements are assumed to be hashable.

    If you need to check uniqueness based on a custom key function, use `PyoIterable::all_unique_by` instead.

    Tip:
        If you already have an existing `Collection`, you can alternatively check uniqueness by comparing the length of the collection to the length of a set created from it.

        On a "worst" case scenario (all elements are unique), this can be a bit faster on large (100k + items) collections, by around 1.15x (i.e 15% faster).

        Or on very small (10 items or less), where the overhead of creating the `Iterator` makes it 2x slower than simply creating the set.

        Altough, at this point, the operation is so fast that the difference is negligible, unless you are doing it in a hot loop.

        All things considered, `all_unique` early-exits on first duplicate can make it orders of magnitude faster, when your probability of duplicates is anything but very low.

    Returns:
        bool: `True` if all elements are unique, `False` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter, Seq, Set
        >>> Iter("ABCB").all_unique()
        False
        >>> Iter("ABCb").all_unique()
        True
        >>> # Alternative way to check uniqueness by comparing lengths:
        >>> collection = Seq((1, 2, 3, 3))
        >>> collection.len() == collection.into(Set).len()
        False

        ```
    """
    return tls.all_unique(iter(self))

all_unique_by(key)

Returns True if all the elements of self transformed by key are unique.

The function returns as soon as the first non-unique element is encountered.

Credits to more-itertools for the implementation.

Parameters:

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

Function to transform items before comparison.

required

Returns:

Name Type Description
bool bool

True if all elements are unique, False otherwise.

Example
>>> from pyochain import Iter
>>> Iter("ABCb").all_unique()
True
>>> Iter("ABCb").all_unique_by(str.lower)
False
Source code in src/pyochain/abc/_iterator.py
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
def all_unique_by[U](self, key: Callable[[T], U]) -> bool:
    """Returns True if all the elements of **self** transformed by **key** are unique.

    The function returns as soon as the first non-unique element is encountered.

    Credits to **more-itertools** for the implementation.

    Args:
        key (Callable[[T], U]): Function to transform items before comparison.

    Returns:
        bool: `True` if all elements are unique, `False` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter("ABCb").all_unique()
        True
        >>> Iter("ABCb").all_unique_by(str.lower)
        False

        ```
    """
    return tls.all_unique_by(iter(self), key)

any(predicate=None)

Tests if any element of the Iterator is truthy.

PyoIterator::.any can optionally take a closure that returns true or false.

It applies this closure to each element of the Iterator, and if any of them return true, then so does PyoIterator::.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
>>> from pyochain import Iter, Range
>>> Iter((0, 1)).any()
True
>>> Range(0, 0).iter().any()
False
>>> def is_even(x: int) -> bool:
...     return x % 2 == 0
>>> Iter((1, 3, 4)).any(is_even)
True
Source code in src/pyochain/abc/_iterator.py
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
def any(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if any element of the `Iterator` is truthy.

    `PyoIterator::.any` can optionally take a closure that returns true or false.

    It applies this closure to each element of the `Iterator`, and if any of them return true, then so does `PyoIterator::.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
        >>> from pyochain import Iter, Range
        >>> Iter((0, 1)).any()
        True
        >>> Range(0, 0).iter().any()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>> Iter((1, 3, 4)).any(is_even)
        True

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

arg_max()

Index of the first occurrence of a maximum value in the Iterator.

Credits to more-itertools for the implementation.

Returns:

Name Type Description
int int

The index of the maximum value.

Example

Basic usage:

>>> from pyochain import Iter, Seq
>>> Iter("abcdefghabcd").arg_max()
7
>>> Iter((0, 1, 2, 3, 3, 2, 1, 0)).arg_max()
3
Identify the best machine learning model:
>>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
>>> accuracy = Seq((68, 61, 84, 72))
>>> # Most accurate model
>>> models.get(accuracy.iter().arg_max()).unwrap()
'knn'
>>> # Best accuracy
>>> accuracy.iter().max()
84

Source code in src/pyochain/abc/_iterator.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
def arg_max(self) -> int:
    """Index of the first occurrence of a maximum value in the `Iterator`.

    Credits to more-itertools for the implementation.

    Returns:
        int: The index of the maximum value.

    Example:
        Basic usage:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter("abcdefghabcd").arg_max()
        7
        >>> Iter((0, 1, 2, 3, 3, 2, 1, 0)).arg_max()
        3

        ```
        Identify the best machine learning model:
        ```python
        >>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
        >>> accuracy = Seq((68, 61, 84, 72))
        >>> # Most accurate model
        >>> models.get(accuracy.iter().arg_max()).unwrap()
        'knn'
        >>> # Best accuracy
        >>> accuracy.iter().max()
        84

        ```
    """
    return max(enumerate(iter(self)), key=itemgetter(1))[0]

arg_max_by(key)

Index of the first occurrence of a maximum value in the Iterator based on a key function.

The key function must accept a single argument and return a transformed, comparable version of each input item.

Credits to more-itertools for the implementation.

Parameters:

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

Function to determine the value for comparison.

required

Returns:

Name Type Description
int int

The index of the maximum value.

Example

Basic usage:

>>> from pyochain import Iter, Seq
>>> Iter(("a", "bbb", "cc")).arg_max_by(len)
1
>>> Iter(("Alice", "bob", "charlie")).arg_max_by(str.lower)
2
Identify the best machine learning model:
>>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
>>> accuracy = Seq(("68", "61", "84", "72"))
>>> # Most accurate model
>>> models.get(accuracy.iter().arg_max_by(int)).unwrap()
'knn'
>>> # Best accuracy
>>> accuracy.iter().max_by(int)
'84'

Source code in src/pyochain/abc/_iterator.py
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
def arg_max_by[U](self, key: Callable[[T], U]) -> int:
    """Index of the first occurrence of a maximum value in the `Iterator` based on a *key* function.

    The *key* function must accept a single argument and return a transformed, comparable version of each input item.

    Credits to more-itertools for the implementation.

    Args:
        key (Callable[[T], U]): Function to determine the value for comparison.

    Returns:
        int: The index of the maximum value.

    Example:
        Basic usage:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter(("a", "bbb", "cc")).arg_max_by(len)
        1
        >>> Iter(("Alice", "bob", "charlie")).arg_max_by(str.lower)
        2

        ```
        Identify the best machine learning model:
        ```python
        >>> models = Seq(("svm", "random forest", "knn", "naïve bayes"))
        >>> accuracy = Seq(("68", "61", "84", "72"))
        >>> # Most accurate model
        >>> models.get(accuracy.iter().arg_max_by(int)).unwrap()
        'knn'
        >>> # Best accuracy
        >>> accuracy.iter().max_by(int)
        '84'

        ```
    """
    return max(enumerate(map(key, iter(self))), key=itemgetter(1))[0]

arg_min()

Index of the first occurrence of a minimum value in the Iterator.

Credits to more-itertools for the implementation.

Returns:

Name Type Description
int int

The index of the minimum value.

Example
>>> from pyochain import Iter, Seq
>>> # Example 1: Basic usage
>>> Iter("efghabcdijkl").arg_min()
4
>>> Iter((3, 2, 1, 0, 4, 2, 1, 0)).arg_min()
3
Source code in src/pyochain/abc/_iterator.py
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
def arg_min(self) -> int:
    """Index of the first occurrence of a minimum value in the `Iterator`.

    Credits to more-itertools for the implementation.

    Returns:
        int: The index of the minimum value.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> # Example 1: Basic usage
        >>> Iter("efghabcdijkl").arg_min()
        4
        >>> Iter((3, 2, 1, 0, 4, 2, 1, 0)).arg_min()
        3

        ```
    """
    return min(enumerate(iter(self)), key=itemgetter(1))[0]

arg_min_by(key)

Index of the first occurrence of a minimum value in the Iterator based on a key function.

The key function must accept a single argument and return a transformed, comparable version of each input item.

Credits to more-itertools for the implementation.

Parameters:

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

Function to determine the value for comparison.

required

Returns:

Name Type Description
int int

The index of the minimum value.

Example

Basic usage:

>>> from pyochain import Iter, Seq
>>> Iter(("aaa", "b", "cc")).arg_min_by(len)
1
>>> Iter(("Alice", "bob", "Charlie")).arg_min_by(str.lower)
0
Identify the best machine learning model:
>>> def cost(x: int) -> float:
...     "Days for a wound to heal given a subject's age."
...     return x**2 - 20 * x + 150
>>>
>>> labels = Seq(("homer", "marge", "bart", "lisa", "maggie"))
>>> ages = Seq((35, 30, 10, 9, 1))
>>> # Fastest healing family member
>>> labels.get(ages.iter().arg_min_by(cost)).unwrap()
'bart'
>>> # Age with fastest healing
>>> ages.iter().min_by(key=cost)
10

Source code in src/pyochain/abc/_iterator.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
def arg_min_by[U](self, key: Callable[[T], U]) -> int:
    """Index of the first occurrence of a minimum value in the `Iterator` based on a *key* function.

    The *key* function must accept a single argument and return a transformed, comparable version of each input item.

    Credits to more-itertools for the implementation.

    Args:
        key (Callable[[T], U]): Function to determine the value for comparison.

    Returns:
        int: The index of the minimum value.

    Example:
        Basic usage:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter(("aaa", "b", "cc")).arg_min_by(len)
        1
        >>> Iter(("Alice", "bob", "Charlie")).arg_min_by(str.lower)
        0

        ```
        Identify the best machine learning model:
        ```python
        >>> def cost(x: int) -> float:
        ...     "Days for a wound to heal given a subject's age."
        ...     return x**2 - 20 * x + 150
        >>>
        >>> labels = Seq(("homer", "marge", "bart", "lisa", "maggie"))
        >>> ages = Seq((35, 30, 10, 9, 1))
        >>> # Fastest healing family member
        >>> labels.get(ages.iter().arg_min_by(cost)).unwrap()
        'bart'
        >>> # Age with fastest healing
        >>> ages.iter().min_by(key=cost)
        10

        ```
    """
    return min(enumerate(map(key, iter(self))), key=itemgetter(1))[0]

chain(*others)

Concatenate self with one or more Iterables, any of which may be infinite.

In other words, it links self and others together, in a chain. 🔗

An infinite Iterable will prevent the rest of the arguments from being included.

This is equivalent to list.extend(), except it is fully lazy and works with any Iterable.

See Also

Iter::insert to add a single element at the beginning of the Iterator.

Parameters:

Name Type Description Default
*others Iterable[T]

Other iterables to concatenate.

()

Returns:

Name Type Description
Self Self

A new Iterator which will first iterate over values from the original Iterator and then over values from the others Iterables.

Example
>>> from pyochain import Iter
>>> Iter((1, 2)).chain((3, 4), [5]).collect()
Seq(1, 2, 3, 4, 5)
>>> Iter((1, 2)).chain(Iter.from_count(3)).take(5).collect()
Seq(1, 2, 3, 4, 5)
Source code in src/pyochain/abc/_iterator.py
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
def chain(self, *others: Iterable[T]) -> Self:
    """Concatenate **self** with one or more `Iterables`, any of which may be infinite.

    In other words, it links **self** and **others** together, in a chain. 🔗

    An infinite `Iterable` will prevent the rest of the arguments from being included.

    This is equivalent to `list.extend()`, except it is fully lazy and works with any `Iterable`.

    See Also:
        [`Iter::insert`][insert] to add a single element at the beginning of the `Iterator`.

    Args:
        *others (Iterable[T]): Other iterables to concatenate.

    Returns:
        Self: A new `Iterator` which will first iterate over values from the original `Iterator` and then over values from the **others** `Iterable`s.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2)).chain((3, 4), [5]).collect()
        Seq(1, 2, 3, 4, 5)
        >>> Iter((1, 2)).chain(Iter.from_count(3)).take(5).collect()
        Seq(1, 2, 3, 4, 5)

        ```
    """
    return self._from_iterable(itertools.chain.from_iterable((iter(self), *others)))

collect(collector)

Transforms the Iterator into a collection.

The most basic pattern in which collect() is used is to turn one collection into another.

You take a collection, call iter() on it, do a bunch of transformations, and then collect() at the end.

You specify the target Collection type by providing a collector function or type.

This can be any Callable that takes an Iterator[T] and returns a Collection[T] of those types.

This is equivalent to Pipeable::into at runtime, but with a few differences:

- A narrower constraint (`Collection[Any]`) to specify the intent
- Better performance (no args/kwargs unpacking).

If you need to pass additional arguments, you can use [Pipeable::into][pyochain.rs.Pipeable.into] instead.

Note

Iter::collect is overriden to provide Seq as the default collector.

Parameters:

Name Type Description Default
collector Callable[[Iterator[T]], R]

Function|type that defines the target collection. R is constrained to a Collection.

required

Returns:

Name Type Description
R R

A materialized Collection containing the collected elements.

Example

>>> from pyochain import Iter, Range, Vec, Dict
>>> data = Range(0, 5)
>>> data.iter().collect(list)
[0, 1, 2, 3, 4]
>>> data.iter().collect(Vec)
Vec(0, 1, 2, 3, 4)
>>> data.iter().map(str).enumerate().collect(Dict)
Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')
Sometimes type checkers can't infer the type of the collector, in which case you can use an explicit type annotation to help them out.

In the example below, without the annotation in collect(),

BasedPyright infer data as Seq[Result[int, Any] | Result[Any, int]] because of the conditional expression in the map(), which is not very useful.

>>> from pyochain import Range, Seq, Ok, Err, Result
>>> data = (
...     Range(0, 5)
...     .iter()
...     .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
...     .collect(Seq[Result[int, int]])
... )
>>> data
Seq(Ok(0), Err(1), Ok(2), Err(3), Ok(4))
Strictly speaking, this is equivalent to annotating the variable at the beginning, but some may prefer this style to keep the type information close to the actual collection operation.

This notably avoid repetition if you collect anything else than the default Seq type.

Source code in src/pyochain/abc/_iterator.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def collect[R: Collection[Any]](self, collector: Callable[[Iterator[T]], R]) -> R:
    """Transforms the `Iterator` into a collection.

    The most basic pattern in which `collect()` is used is to turn one collection into another.

    You take a collection, call `iter()` on it, do a bunch of transformations, and then `collect()` at the end.

    You specify the target `Collection` type by providing a **collector** function or type.

    This can be any `Callable` that takes an `Iterator[T]` and returns a `Collection[T]` of those types.

    This is equivalent to `Pipeable::into` at runtime, but with a few differences:

        - A narrower constraint (`Collection[Any]`) to specify the intent
        - Better performance (no args/kwargs unpacking).

    If you need to pass additional arguments, you can use [`Pipeable::into`][Pipeable.into] instead.

    Note:
        `Iter::collect` is overriden to provide `Seq` as the default **collector**.

    Args:
        collector (Callable[[Iterator[T]], R]): Function|type that defines the target collection. `R` is constrained to a `Collection`.

    Returns:
        R: A materialized `Collection` containing the collected elements.

    Example:
        ```python
        >>> from pyochain import Iter, Range, Vec, Dict
        >>> data = Range(0, 5)
        >>> data.iter().collect(list)
        [0, 1, 2, 3, 4]
        >>> data.iter().collect(Vec)
        Vec(0, 1, 2, 3, 4)
        >>> data.iter().map(str).enumerate().collect(Dict)
        Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')

        ```
        Sometimes type checkers can't infer the type of the collector, in which case you can use an explicit type annotation to help them out.

        In the example below, without the annotation in `collect()`,

        BasedPyright infer `data` as `Seq[Result[int, Any] | Result[Any, int]]` because of the conditional expression in the `map()`, which is not very useful.
        ```python
        >>> from pyochain import Range, Seq, Ok, Err, Result
        >>> data = (
        ...     Range(0, 5)
        ...     .iter()
        ...     .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
        ...     .collect(Seq[Result[int, int]])
        ... )
        >>> data
        Seq(Ok(0), Err(1), Ok(2), Err(3), Ok(4))

        ```
        Strictly speaking, this is equivalent to annotating the variable at the beginning, but some may prefer this style to keep the type information close to the actual collection operation.

        This notably avoid repetition if you collect anything else than the default `Seq` type.
    """
    return collector(iter(self))

collect_into(collection)

collect_into(collection: Vec[T]) -> Vec[T]
collect_into(
    collection: PyoMutableSequence[T],
) -> PyoMutableSequence[T]
collect_into(collection: list[T]) -> list[T]

Collects all the items from the Iterator into a MutableSequence.

The MutableSequence is then returned, so the call chain can be continued.

This is useful when you already have a MutableSequence and want to add the Iterator items to it.

This method is a convenience method to call MutableSequence.extend(), but instead of being called on a MutableSequence, it's called on an Iterator.

Parameters:

Name Type Description Default
collection MutableSequence[T]

A mutable collection to collect items into.

required

Returns:

Type Description
MutableSequence[T]

MutableSequence[T]: The same mutable collection passed as argument, now containing the collected items.

Example

Basic usage:

>>> from pyochain import Seq, Iter, Vec
>>> a = Seq((1, 2, 3))
>>> vec = Vec.from_ref([0, 1])
>>> a.iter().map(lambda x: x * 2).collect_into(vec)
Vec(0, 1, 2, 4, 6)
>>> a.iter().map(lambda x: x * 10).collect_into(vec)
Vec(0, 1, 2, 4, 6, 10, 20, 30)
The returned mutable sequence can be used to continue the call chain:
>>> from pyochain import Seq, Vec
>>> a = Seq((1, 2, 3))
>>> vec = Vec(())
>>> a.iter().collect_into(vec).len() == vec.len()
True
>>> a.iter().collect_into(vec).len() == vec.len()
True

Source code in src/pyochain/abc/_iterator.py
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
def collect_into(self, collection: MutableSequence[T]) -> MutableSequence[T]:
    """Collects all the items from the `Iterator` into a `MutableSequence`.

    The `MutableSequence` is then returned, so the call chain can be continued.

    This is useful when you already have a `MutableSequence` and want to add the `Iterator` items to it.

    This method is a convenience method to call `MutableSequence.extend()`, but instead of being called on a `MutableSequence`, it's called on an `Iterator`.

    Args:
        collection (MutableSequence[T]): A mutable collection to collect items into.

    Returns:
        MutableSequence[T]: The same mutable collection passed as argument, now containing the collected items.

    Example:
        Basic usage:
        ```python
        >>> from pyochain import Seq, Iter, Vec
        >>> a = Seq((1, 2, 3))
        >>> vec = Vec.from_ref([0, 1])
        >>> a.iter().map(lambda x: x * 2).collect_into(vec)
        Vec(0, 1, 2, 4, 6)
        >>> a.iter().map(lambda x: x * 10).collect_into(vec)
        Vec(0, 1, 2, 4, 6, 10, 20, 30)

        ```
        The returned mutable sequence can be used to continue the call chain:
        ```python
        >>> from pyochain import Seq, Vec
        >>> a = Seq((1, 2, 3))
        >>> vec = Vec(())
        >>> a.iter().collect_into(vec).len() == vec.len()
        True
        >>> a.iter().collect_into(vec).len() == vec.len()
        True

        ```
    """
    collection.extend(iter(self))
    return collection

compress(*selectors)

Filter elements using a boolean selector iterable.

Parameters:

Name Type Description Default
*selectors bool

Boolean values indicating which elements to keep.

()

Returns:

Name Type Description
Self Self

An Iterator of the items selected by the boolean selectors.

Example
>>> from pyochain import Iter
>>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect()
Seq('A', 'C', 'E', 'F')
Source code in src/pyochain/abc/_iterator.py
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
def compress(self, *selectors: bool) -> Self:
    """Filter elements using a boolean selector iterable.

    Args:
        *selectors (bool): Boolean values indicating which elements to keep.

    Returns:
        Self: An `Iterator` of the items selected by the boolean selectors.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect()
        Seq('A', 'C', 'E', 'F')

        ```
    """
    return self._from_iterable(itertools.compress(iter(self), selectors))

count()

Consume the Iterator and return the number of elements it contained.

Returns:

Name Type Description
int int

The count of elements.

Example
>>> from pyochain import Iter
>>> data = Iter((1, 2, 3))
>>> data.count()
3
>>> # data is now empty
>>> data.count()
0
Source code in src/pyochain/abc/_iterator.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def count(self) -> int:
    """Consume the `Iterator` and return the number of elements it contained.

    Returns:
        int: The count of elements.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> data = Iter((1, 2, 3))
        >>> data.count()
        3
        >>> # data is now empty
        >>> data.count()
        0

        ```
    """
    return tls.length(iter(self))

cycle()

Repeat the Iterator indefinitely.

Warning

This creates an infinite Iterator.

Be sure to use Iter::take or Iter::slice to limit the number of items taken.

See Also

[Iter::repeat][repeat] to repeat self as elements (Iter[Self]).

Returns:

Name Type Description
Self Self

A new Iterator that cycles through the elements indefinitely.

Example
>>> from pyochain import Iter
>>> Iter((1, 2)).cycle().take(5).collect()
Seq(1, 2, 1, 2, 1)
Source code in src/pyochain/abc/_iterator.py
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
def cycle(self) -> Self:
    """Repeat the `Iterator` indefinitely.

    Warning:
        This creates an infinite `Iterator`.

        Be sure to use [`Iter::take`][take] or [`Iter::slice`][slice] to limit the number of items taken.

    See Also:
        [`Iter::repeat`][repeat] to repeat *self* as elements (`Iter[Self]`).

    Returns:
        Self: A new `Iterator` that cycles through the elements indefinitely.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2)).cycle().take(5).collect()
        Seq(1, 2, 1, 2, 1)

        ```
    """
    return self._from_iterable(itertools.cycle(iter(self)))

eq(other)

Return True if self and other contain the same items in the same order.

Comparison is performed element by element.

Two Iterables are equal only if:

  • every compared pair of elements is equal
  • and both iterables are exhausted at the same time
Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True when both iterables yield the same sequence of values.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).eq(Seq((1, 2, 3)))
True
>>> Iter((1, 2, 3)).eq((1, 2, 4))
False
>>> Iter((1, 2, 3)).eq((1, 2))
False
>>> Iter((1, 2)).eq((1, 2, 3))
False
Source code in src/pyochain/abc/_iterator.py
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
def eq(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** and *other* contain the same items in the same order.

    Comparison is performed element by element.

    Two `Iterable`s are equal only if:

    - every compared pair of elements is equal
    - and both iterables are exhausted at the same time

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` when both iterables yield the same sequence of values.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 3)).eq(Seq((1, 2, 3)))
        True
        >>> Iter((1, 2, 3)).eq((1, 2, 4))
        False
        >>> Iter((1, 2, 3)).eq((1, 2))
        False
        >>> Iter((1, 2)).eq((1, 2, 3))
        False

        ```
    """
    return tls.eq(iter(self), other)

find(predicate)

Searches for an element of an iterator that satisfies a predicate.

Takes a closure that returns true or false as predicate, and applies it to each element of the iterator.

Parameters:

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

Function to evaluate each item.

required

Returns:

Type Description
Option[T]

Option[T]: The first element satisfying the predicate. Some(value) if found, NONE otherwise.

Example
>>> from pyochain import Iter, Range
>>> def gt_five(x: int) -> bool:
...     return x > 5
>>>
>>> def gt_nine(x: int) -> bool:
...     return x > 9
>>> data = Range(0, 10)
>>> data.iter().find(predicate=gt_five)
Some(6)
>>> data.iter().find(predicate=gt_nine).unwrap_or("missing")
'missing'
Source code in src/pyochain/abc/_iterator.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
def find(self, predicate: Callable[[T], bool]) -> Option[T]:
    """Searches for an element of an iterator that satisfies a `predicate`.

    Takes a closure that returns true or false as `predicate`, and applies it to each element of the iterator.

    Args:
        predicate (Callable[[T], bool]): Function to evaluate each item.

    Returns:
        Option[T]: The first element satisfying the predicate. `Some(value)` if found, `NONE` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter, Range
        >>> def gt_five(x: int) -> bool:
        ...     return x > 5
        >>>
        >>> def gt_nine(x: int) -> bool:
        ...     return x > 9
        >>> data = Range(0, 10)
        >>> data.iter().find(predicate=gt_five)
        Some(6)
        >>> data.iter().find(predicate=gt_nine).unwrap_or("missing")
        'missing'

        ```
    """
    return option(next(filter(predicate, self), None))

fold(init, func)

Fold every element of the Iterator into an accumulator by applying an operation, returning the final result.

Parameters:

Name Type Description Default
init B

Initial value for the accumulator.

required
func Callable[[B, T], B]

Function that takes the accumulator and current element, returning the new accumulator value.

required

Returns:

Name Type Description
B B

The final accumulated value.

Note

This is similar to reduce() but with an initial value.

Example
>>> from pyochain import Iter
>>> data = (1, 2, 3)
>>> Iter(data).fold(0, lambda acc, x: acc + x)
6
>>> Iter(data).fold(10, lambda acc, x: acc + x)
16
>>> Iter(("a", "b", "c")).fold("", lambda acc, x: acc + x)
'abc'
Source code in src/pyochain/abc/_iterator.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
def fold[B](self, init: B, func: Callable[[B, T], B]) -> B:
    """Fold every element of the `Iterator` into an accumulator by applying an operation, returning the final result.

    Args:
        init (B): Initial value for the accumulator.
        func (Callable[[B, T], B]): Function that takes the accumulator and current element,
            returning the new accumulator value.

    Returns:
        B: The final accumulated value.

    Note:
        This is similar to `reduce()` but with an initial value.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> data = (1, 2, 3)
        >>> Iter(data).fold(0, lambda acc, x: acc + x)
        6
        >>> Iter(data).fold(10, lambda acc, x: acc + x)
        16
        >>> Iter(("a", "b", "c")).fold("", lambda acc, x: acc + x)
        'abc'

        ```
    """
    return functools.reduce(func, self, init)

fold_star(init, func, *args, **kwargs)

fold_star(
    init: B,
    func: Callable[[Any], B],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[Concatenate[B, T1, T2, P], B],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[Concatenate[B, T1, T2, T3, P], B],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[Concatenate[B, T1, T2, T3, T4, P], B],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[B, T1, T2, T3, T4, T5, P], B
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[B, T1, T2, T3, T4, T5, T6, P], B
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[B, T1, T2, T3, T4, T5, T6, T7, P], B
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[B, T1, T2, T3, T4, T5, T6, T7, T8, P], B
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[
            B, T1, T2, T3, T4, T5, T6, T7, T8, T9, P
        ],
        B,
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B
fold_star(
    init: B,
    func: Callable[
        Concatenate[
            B, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, P
        ],
        B,
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B

Fold every element of the Iterator into an accumulator by applying an operation, returning the final result.

Use this when the items of the Iterator are themselves iterables (e.g., tuples), and you want to unpack them as arguments to the folding function.

Parameters:

Name Type Description Default
init B

Initial value for the accumulator.

required
func Callable[..., B]

Function that takes the accumulator and current element, returning the new accumulator value.

required
*args P.args

Additional positional arguments to pass to func.

()
**kwargs P.kwargs

Additional keyword arguments to pass to func.

{}

Returns:

Name Type Description
B B

The final accumulated value.

Note

This is similar to Iter::reduce but with an initial value.

Example
>>> from pyochain import Iter
>>> data = ((1, 2), (3, 4))
>>> Iter(data).fold_star(0, lambda acc, x, y: acc + x + y)
10
>>> data = (("a", "b"), ("c", "d"))
>>> Iter(data).fold_star("", lambda acc, x, y: acc + x + y)
'abcd'
Source code in src/pyochain/abc/_iterator.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def fold_star[U: Iterable[Any], **P, B](
    self: PyoIterator[U],
    init: B,
    func: Callable[..., B],
    *args: P.args,
    **kwargs: P.kwargs,
) -> B:
    """Fold every element of the `Iterator` into an accumulator by applying an operation, returning the final result.

    Use this when the items of the `Iterator` are themselves iterables (e.g., tuples), and you want to unpack them as arguments to the folding function.

    Args:
        init (B): Initial value for the accumulator.
        func (Callable[..., B]): Function that takes the accumulator and current element, returning the new accumulator value.
        *args (P.args): Additional positional arguments to pass to **func**.
        **kwargs (P.kwargs): Additional keyword arguments to pass to **func**.

    Returns:
        B: The final accumulated value.

    Note:
        This is similar to `Iter::reduce` but with an initial value.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> data = ((1, 2), (3, 4))
        >>> Iter(data).fold_star(0, lambda acc, x, y: acc + x + y)
        10
        >>> data = (("a", "b"), ("c", "d"))
        >>> Iter(data).fold_star("", lambda acc, x, y: acc + x + y)
        'abcd'

        ```
    """

    def _reducer(acc: B, item: U) -> B:
        return func(acc, *item, *args, **kwargs)

    return functools.reduce(_reducer, self, init)

for_each(func, *args, **kwargs)

Consume the Iterator by applying a function to each element in the Iterable.

Is a terminal operation, and is useful for functions that have side effects, or when you want to force evaluation of a lazy iterable.

Parameters:

Name Type Description Default
func Callable[Concatenate[T, P], Any]

Function to apply to each element.

required
*args P.args

Positional arguments for the function.

()
**kwargs P.kwargs

Keyword arguments for the function.

{}
Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).for_each(lambda x: print(x + 1))
2
3
4
Source code in src/pyochain/abc/_iterator.py
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
def for_each[**P](
    self,
    func: Callable[Concatenate[T, P], Any],  # pyright: ignore[reportExplicitAny]
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """Consume the `Iterator` by applying a function to each element in the `Iterable`.

    Is a terminal operation, and is useful for functions that have side effects,
    or when you want to force evaluation of a lazy iterable.

    Args:
        func (Callable[Concatenate[T, P], Any]): Function to apply to each element.
        *args (P.args): Positional arguments for the function.
        **kwargs (P.kwargs): Keyword arguments for the function.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).for_each(lambda x: print(x + 1))
        2
        3
        4

        ```
    """
    tls.for_each(iter(self), func, *args, **kwargs)

for_each_star(func, *args, **kwargs)

for_each_star(
    func: Callable[Concatenate[T1, T2, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[Concatenate[T1, T2, T3, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[Concatenate[T1, T2, T3, T4, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[Concatenate[T1, T2, T3, T4, T5, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[
        Concatenate[T1, T2, T3, T4, T5, T6, P], R
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[
        Concatenate[T1, T2, T3, T4, T5, T6, T7, P], R
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[
        Concatenate[T1, T2, T3, T4, T5, T6, T7, T8, P], R
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[
        Concatenate[T1, T2, T3, T4, T5, T6, T7, T8, T9, P],
        R,
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None
for_each_star(
    func: Callable[
        Concatenate[
            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, P
        ],
        R,
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None

Consume the Iterator by applying a function to each unpacked item in the Iterable element.

Is a terminal operation, and is useful for functions that have side effects, or when you want to force evaluation of a lazy iterable.

Each item yielded by the Iterator is expected to be an Iterable itself (e.g., a tuple or list), and its elements are unpacked as arguments to the provided function.

This is often used after methods like zip() or enumerate() that yield tuples.

Parameters:

Name Type Description Default
func Callable[..., R]

Function to apply to each unpacked element.

required
*args P.args

Positional arguments for the function.

()
**kwargs P.kwargs

Keyword arguments for the function.

{}
Example
>>> from pyochain import Iter
>>> Iter(((1, 2), (3, 4))).for_each_star(lambda x, y: print(x + y))
3
7
Source code in src/pyochain/abc/_iterator.py
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def for_each_star[U: tuple[Any, ...], **P, R](
    self: PyoIterator[U],
    func: Callable[..., R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """Consume the `Iterator` by applying a function to each unpacked item in the `Iterable` element.

    Is a terminal operation, and is useful for functions that have side effects,
    or when you want to force evaluation of a lazy iterable.

    Each item yielded by the `Iterator` is expected to be an `Iterable` itself (e.g., a tuple or list),
    and its elements are unpacked as arguments to the provided function.

    This is often used after methods like `zip()` or `enumerate()` that yield tuples.

    Args:
        func (Callable[..., R]): Function to apply to each unpacked element.
        *args (P.args): Positional arguments for the function.
        **kwargs (P.kwargs): Keyword arguments for the function.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter(((1, 2), (3, 4))).for_each_star(lambda x, y: print(x + y))
        3
        7

        ```
    """
    tls.for_each_star(iter(self), func, *args, **kwargs)

ge(other)

Return True if self is lexicographically greater than or equal to other.

Comparison is performed element by element, like Python sequence ordering.

The first differing pair decides the result.

If all compared elements are equal and one iterable ends first, the longer iterable is considered greater.

Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self is greater than other, or equal to it.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).ge((1, 2))
True
>>> Iter((1, 2, 3)).ge((1, 2, 3))
True
>>> Iter((1, 2)).ge((1, 2, 3))
False
Source code in src/pyochain/abc/_iterator.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def ge(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** is lexicographically greater than or equal to *other*.

    Comparison is performed element by element, like Python sequence ordering.

    The first differing pair decides the result.

    If all compared elements are equal and one iterable ends first, the longer iterable is considered
    greater.

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` if **self** is greater than *other*, or equal to it.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).ge((1, 2))
        True
        >>> Iter((1, 2, 3)).ge((1, 2, 3))
        True
        >>> Iter((1, 2)).ge((1, 2, 3))
        False

        ```
    """
    return tls.ge(iter(self), other)

gt(other)

Return True if self is lexicographically strictly greater than other.

The first differing pair of elements decides the result.

If all compared elements are equal, the longer iterable is strictly greater than the shorter one.

Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly after other.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).gt((1, 2))
True
>>> Iter((1, 3)).gt((1, 2, 9))
True
>>> Iter((1, 2)).gt((1, 2, 3))
False
Source code in src/pyochain/abc/_iterator.py
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
def gt(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** is lexicographically strictly greater than *other*.

    The first differing pair of elements decides the result.

    If all compared elements are equal, the longer iterable is strictly greater than the shorter one.

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` if **self** compares strictly after *other*.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).gt((1, 2))
        True
        >>> Iter((1, 3)).gt((1, 2, 9))
        True
        >>> Iter((1, 2)).gt((1, 2, 3))
        False

        ```
    """
    return tls.gt(iter(self), other)

insert(value)

Prepend the value to the Iterator.

Note

This can be considered the equivalent as list.append(), but for a lazy Iterator.

However, append add the value at the end, while insert add it at the beginning.

See Also

Iter::chain to add multiple elements at the end of the Iterator.

Parameters:

Name Type Description Default
value T

The value to prepend.

required

Returns:

Name Type Description
Self Self

A new Iterable wrapper with the value prepended.

Example
>>> from pyochain import Iter
>>> Iter((2, 3)).insert(1).collect()
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def insert(self, value: T) -> Self:
    """Prepend the *value* to the `Iterator`.

    Note:
        This can be considered the equivalent as `list.append()`, but for a lazy `Iterator`.

        However, append add the value at the **end**, while insert add it at the **beginning**.

    See Also:
        [`Iter::chain`][chain] to add multiple elements at the end of the `Iterator`.

    Args:
        value (T): The value to prepend.

    Returns:
        Self: A new Iterable wrapper with the value prepended.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((2, 3)).insert(1).collect()
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(itertools.chain((value,), iter(self)))

intersperse(element)

Creates a new Iterator which places a copy of separator between adjacent items of the original iterator.

Parameters:

Name Type Description Default
element T

The element to interpose between items.

required

Returns:

Name Type Description
Self Self

A new Iterator with the element interposed.

Example
>>> from pyochain import Iter
>>> # Simple example with numbers
>>> Iter((1, 2, 3)).intersperse(0).collect()
Seq(1, 0, 2, 0, 3)
>>> # Useful when chaining with other operations
>>> Iter([10, 20, 30]).intersperse(5).sum()
70
>>> # Inserting separators between groups, then flattening
>>> Iter(((1, 2), (3, 4), (5, 6))).intersperse([-1]).flatten().collect()
Seq(1, 2, -1, 3, 4, -1, 5, 6)
Source code in src/pyochain/abc/_iterator.py
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
def intersperse(self, element: T) -> Self:
    """Creates a new `Iterator` which places a copy of separator between adjacent items of the original iterator.

    Args:
        element (T): The element to interpose between items.

    Returns:
        Self: A new `Iterator` with the element interposed.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> # Simple example with numbers
        >>> Iter((1, 2, 3)).intersperse(0).collect()
        Seq(1, 0, 2, 0, 3)
        >>> # Useful when chaining with other operations
        >>> Iter([10, 20, 30]).intersperse(5).sum()
        70
        >>> # Inserting separators between groups, then flattening
        >>> Iter(((1, 2), (3, 4), (5, 6))).intersperse([-1]).flatten().collect()
        Seq(1, 2, -1, 3, 4, -1, 5, 6)

        ```
    """
    return self._from_iterable(tls.Intersperse(iter(self), element))

is_sorted(*, reverse=False, strict=False)

Returns True if the items of the Iterator are in sorted order.

The elements of the Iterator must support comparison operations.

The function returns False after encountering the first out-of-order item.

If there are no out-of-order items, the Iterator is exhausted.

Credits to more-itertools for the implementation.

See Also

PyoIterator::is_sorted_by if your elements do not support comparison operations directly, or you want to sort based on a specific attribute or transformation.

Parameters:

Name Type Description Default
reverse bool

Whether to check for descending order.

False
strict bool

Whether to enforce strict sorting (no equal elements).

False

Returns:

Name Type Description
bool bool

True if items are sorted according to the criteria, False otherwise.

Example

>>> from pyochain import Iter
>>> Iter((1, 2, 3, 4, 5)).is_sorted()
True
If strict, tests for strict sorting, that is, returns False if equal elements are found:
>>> Iter([1, 2, 2]).is_sorted()
True
>>> Iter([1, 2, 2]).is_sorted(strict=True)
False

Source code in src/pyochain/abc/_iterator.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
def is_sorted[U: SupportsComparison[Any]](
    self: PyoIterator[U], *, reverse: bool = False, strict: bool = False
) -> bool:
    """Returns `True` if the items of the `Iterator` are in sorted order.

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

    The function returns `False` after encountering the first out-of-order item.

    If there are no out-of-order items, the `Iterator` is exhausted.

    Credits to **more-itertools** for the implementation.

    See Also:
        [`PyoIterator::is_sorted_by`][is_sorted_by] if your elements do not support comparison operations directly, or you want to sort based on a specific attribute or transformation.

    Args:
        reverse (bool): Whether to check for descending order.
        strict (bool): Whether to enforce strict sorting (no equal elements).

    Returns:
        bool: `True` if items are sorted according to the criteria, `False` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3, 4, 5)).is_sorted()
        True

        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        >>> Iter([1, 2, 2]).is_sorted()
        True
        >>> Iter([1, 2, 2]).is_sorted(strict=True)
        False

        ```
    """
    return tls.is_sorted(iter(self), reverse=reverse, strict=strict)

is_sorted_by(key, *, reverse=False, strict=False)

Returns True if the items of the Iterator are in sorted order according to the key function.

The function returns False after encountering the first out-of-order item.

If there are no out-of-order items, the Iterator is exhausted.

Credits to more-itertools for the implementation.

Parameters:

Name Type Description Default
key Callable[[T], SupportsComparison[Any]]

Function to extract a comparison key from each element.

required
reverse bool

Whether to check for descending order.

False
strict bool

Whether to enforce strict sorting (no equal elements).

False

Returns:

Name Type Description
bool bool

True if items are sorted according to the criteria, False otherwise.

Example

>>> from pyochain import Iter
>>> Iter(["1", "2", "3", "4", "5"]).is_sorted_by(int)
True
>>> Iter(["5", "4", "3", "1", "2"]).is_sorted_by(int, reverse=True)
False
If strict, tests for strict sorting, that is, returns False if equal elements are found:
>>> Iter(["1", "2", "2"]).is_sorted_by(int)
True
>>> Iter(["1", "2", "2"]).is_sorted_by(key=int, strict=True)
False

Source code in src/pyochain/abc/_iterator.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
def is_sorted_by(
    self,
    key: Callable[[T], SupportsComparison[Any]],  # pyright: ignore[reportExplicitAny]
    *,
    reverse: bool = False,
    strict: bool = False,
) -> bool:
    """Returns `True` if the items of the `Iterator` are in sorted order according to the key function.

    The function returns `False` after encountering the first out-of-order item.

    If there are no out-of-order items, the `Iterator` is exhausted.

    Credits to **more-itertools** for the implementation.

    Args:
        key (Callable[[T], SupportsComparison[Any]]): Function to extract a comparison key from each element.
        reverse (bool): Whether to check for descending order.
        strict (bool): Whether to enforce strict sorting (no equal elements).

    Returns:
        bool: `True` if items are sorted according to the criteria, `False` otherwise.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter(["1", "2", "3", "4", "5"]).is_sorted_by(int)
        True
        >>> Iter(["5", "4", "3", "1", "2"]).is_sorted_by(int, reverse=True)
        False

        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        >>> Iter(["1", "2", "2"]).is_sorted_by(int)
        True
        >>> Iter(["1", "2", "2"]).is_sorted_by(key=int, strict=True)
        False

        ```
    """
    return tls.is_sorted_by(iter(self), key, reverse=reverse, strict=strict)

join(sep)

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

This is equivalent to the built-in str.join() method, but as a method on the Iterator itself.

Parameters:

Name Type Description Default
sep str

Separator to use between elements.

required

Returns:

Name Type Description
str str

The joined string.

Example
>>> from pyochain import Iter
>>> Iter(("a", "b", "c")).join("-")
'a-b-c'
Source code in src/pyochain/abc/_iterator.py
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def join(self: PyoIterable[str], sep: str) -> str:
    """Join all elements of the `Iterator` into a single `str`, with a specified separator.

    This is equivalent to the built-in `str.join()` method, but as a method on the `Iterator` itself.

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

    Returns:
        str: The joined string.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter(("a", "b", "c")).join("-")
        'a-b-c'

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

le(other)

Return True if self is lexicographically less than or equal to other.

Comparison is performed element by element, like Python sequence ordering.

The first differing pair decides the result.

If all compared elements are equal and one iterable ends first, the shorter iterable is considered smaller.

Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self is smaller than other, or equal to it.

Example
>>> from pyochain import Iter
>>> Iter((1, 2)).le((1, 2, 3))
True
>>> Iter((1, 2, 3)).le((1, 2, 3))
True
>>> Iter((1, 3)).le((1, 2, 9))
False
Source code in src/pyochain/abc/_iterator.py
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
def le(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** is lexicographically less than or equal to *other*.

    Comparison is performed element by element, like Python sequence ordering.

    The first differing pair decides the result.

    If all compared elements are equal and one iterable ends first, the shorter iterable is considered smaller.

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` if **self** is smaller than *other*, or equal to it.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2)).le((1, 2, 3))
        True
        >>> Iter((1, 2, 3)).le((1, 2, 3))
        True
        >>> Iter((1, 3)).le((1, 2, 9))
        False

        ```
    """
    return tls.le(iter(self), other)

lt(other)

Return True if self is lexicographically strictly less than other.

The first differing pair of elements decides the result.

If all compared elements are equal, a shorter iterable is strictly smaller than a longer one.

Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly before other.

Example
>>> from pyochain import Iter
>>> Iter((1, 2)).lt((1, 2, 3))
True
>>> Iter((1, 2, 3)).lt((1, 2, 3))
False
>>> Iter((1, 2, 3)).lt((1, 3))
True
Source code in src/pyochain/abc/_iterator.py
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
def lt(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** is lexicographically strictly less than *other*.

    The first differing pair of elements decides the result.

    If all compared elements are equal, a shorter iterable is strictly smaller than a longer one.

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` if **self** compares strictly before *other*.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2)).lt((1, 2, 3))
        True
        >>> Iter((1, 2, 3)).lt((1, 2, 3))
        False
        >>> Iter((1, 2, 3)).lt((1, 3))
        True

        ```
    """
    return tls.lt(iter(self), other)

max()

Return the maximum element of the Iterator.

The elements of the Iterator 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
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).max()
3
Source code in src/pyochain/abc/_iterator.py
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
def max[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
    """Return the maximum element of the `Iterator`.

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

    For comparing elements using a custom **key** function, use [`max_by`][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
        >>> from pyochain import Iter
        >>> Iter((3, 1, 2)).max()
        3

        ```
    """
    return max(iter(self))

max_by(key)

Return the maximum element of the Iterator 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
>>> from pyochain import Seq
>>> from dataclasses import dataclass
>>>
>>> @dataclass
... class Person:
...     name: str
...     age: int
...     is_student: bool
...
...     def get_discount(self) -> float:
...         return 0.1 if self.is_student else 0.0
>>>
>>> alice = Person("Alice", 30, False)
>>> bob = Person("Bob", 22, True)
>>> charlie = Person("Charlie", 25, False)
>>> persons = Seq((alice, bob, charlie))
>>>
>>> persons.iter().max_by(lambda p: p.age).name
'Alice'
>>> persons.iter().max_by(lambda p: p.name).name
'Charlie'
>>> persons.iter().max_by(Person.get_discount).name
'Bob'
Source code in src/pyochain/abc/_iterator.py
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
def max_by[U: SupportsRichComparison[Any]](self, key: Callable[[T], U]) -> T:
    """Return the maximum element of the `Iterator` 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
        >>> from pyochain import Seq
        >>> from dataclasses import dataclass
        >>>
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        ...     is_student: bool
        ...
        ...     def get_discount(self) -> float:
        ...         return 0.1 if self.is_student else 0.0
        >>>
        >>> alice = Person("Alice", 30, False)
        >>> bob = Person("Bob", 22, True)
        >>> charlie = Person("Charlie", 25, False)
        >>> persons = Seq((alice, bob, charlie))
        >>>
        >>> persons.iter().max_by(lambda p: p.age).name
        'Alice'
        >>> persons.iter().max_by(lambda p: p.name).name
        'Charlie'
        >>> persons.iter().max_by(Person.get_discount).name
        'Bob'

        ```
    """
    return max(iter(self), key=key)

min()

Return the minimum of the Iterator.

The elements of the Iterator 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
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).min()
1
Source code in src/pyochain/abc/_iterator.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
def min[U: SupportsRichComparison[Any]](self: PyoIterable[U]) -> U:
    """Return the minimum of the `Iterator`.

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

    For comparing elements using a custom **key** function, use [`min_by`][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
        >>> from pyochain import Iter
        >>> Iter((3, 1, 2)).min()
        1

        ```
    """
    return min(iter(self))

min_by(key)

Return the minimum element of the Iterator 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
>>> from pyochain import Seq
>>> from dataclasses import dataclass
>>>
>>> @dataclass
... class Person:
...     name: str
...     age: int
...     is_student: bool
...
...     def get_discount(self) -> float:
...         return 0.1 if self.is_student else 0.0
>>>
>>> alice = Person("Alice", 30, False)
>>> bob = Person("Bob", 22, True)
>>> charlie = Person("Charlie", 25, False)
>>> persons = Seq((alice, bob, charlie))
>>>
>>> persons.iter().min_by(lambda p: p.age).name
'Bob'
>>> persons.iter().min_by(lambda p: p.name).name
'Alice'
>>> persons.iter().min_by(Person.get_discount).name
'Alice'
Source code in src/pyochain/abc/_iterator.py
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
def min_by[U: SupportsRichComparison[Any]](self, key: Callable[[T], U]) -> T:
    """Return the minimum element of the `Iterator` 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
        >>> from pyochain import Seq
        >>> from dataclasses import dataclass
        >>>
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        ...     is_student: bool
        ...
        ...     def get_discount(self) -> float:
        ...         return 0.1 if self.is_student else 0.0
        >>>
        >>> alice = Person("Alice", 30, False)
        >>> bob = Person("Bob", 22, True)
        >>> charlie = Person("Charlie", 25, False)
        >>> persons = Seq((alice, bob, charlie))
        >>>
        >>> persons.iter().min_by(lambda p: p.age).name
        'Bob'
        >>> persons.iter().min_by(lambda p: p.name).name
        'Alice'
        >>> persons.iter().min_by(Person.get_discount).name
        'Alice'

        ```
    """
    return min(iter(self), key=key)

ne(other)

Return True if self and other differ in value or length.

This is the logical opposite of eq().

The result becomes True as soon as:

  • a pair of compared elements is not equal
  • or one iterable ends before the other
Note

This consumes any Iterator instances involved in the comparison, including self and other when other is itself an iterator.

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True when the two iterables are not equal.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).ne(Seq((1, 2, 3)))
False
>>> Iter((1, 2, 3)).ne((1, 2, 4))
True
>>> Iter((1, 2, 3)).ne((1, 2))
True
Source code in src/pyochain/abc/_iterator.py
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
def ne(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** and *other* differ in value or length.

    This is the logical opposite of `eq()`.

    The result becomes `True` as soon as:

    - a pair of compared elements is not equal
    - or one iterable ends before the other

    Note:
        This consumes any `Iterator` instances involved in the comparison,
        including **self** and *other* when *other* is itself an iterator.

    Args:
        other (Iterable[T]): Another `Iterable[T]` to compare against.

    Returns:
        bool: `True` when the two iterables are not equal.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 3)).ne(Seq((1, 2, 3)))
        False
        >>> Iter((1, 2, 3)).ne((1, 2, 4))
        True
        >>> Iter((1, 2, 3)).ne((1, 2))
        True

        ```
    """
    return tls.ne(iter(self), other)

next()

Return the next element in the Iterator.

The actual __next__() method must be conform to the Python Iterator Protocol, and is what will be actually called if you iterate over the PyoIterator instance.

PyoIterator::next is a convenience method that wraps the result in an Option to handle exhaustion gracefully, for custom use cases.

Returns:

Type Description
Option[T]

Option[T]: The next element in the iterator. Some[T], or NONE if the iterator is exhausted.

Example
>>> from pyochain import Seq
>>> it = Seq((1, 2, 3)).iter()
>>> it.next().unwrap()
1
>>> it.next().unwrap()
2
Source code in src/pyochain/abc/_iterator.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def next(self) -> Option[T]:
    """Return the next element in the `Iterator`.

    The actual `__next__()` method must be conform to the Python `Iterator` Protocol, and is what will be actually called if you iterate over the `PyoIterator` instance.

    `PyoIterator::next` is a convenience method that wraps the result in an `Option` to handle exhaustion gracefully, for custom use cases.

    Returns:
        Option[T]: The next element in the iterator. `Some[T]`, or `NONE` if the iterator is exhausted.

    Example:
        ```python
        >>> from pyochain import Seq
        >>> it = Seq((1, 2, 3)).iter()
        >>> it.next().unwrap()
        1
        >>> it.next().unwrap()
        2

        ```
    """
    return option(next(self, None))

nth(n)

Return the nth item of the Iterable at the specified n.

This is similar to __getitem__ but for lazy Iterators.

If n is out of bounds, returns NONE.

Parameters:

Name Type Description Default
n int

The index of the item to retrieve.

required

Returns:

Type Description
Option[T]

Option[T]: Some(item) at the specified n.

Example
>>> from pyochain import Iter
>>> Iter([10, 20]).nth(1)
Some(20)
>>> Iter([10, 20]).nth(3)
NONE
Source code in src/pyochain/abc/_iterator.py
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
def nth(self, n: int) -> Option[T]:
    """Return the nth item of the `Iterable` at the specified *n*.

    This is similar to `__getitem__` but for lazy `Iterators`.

    If *n* is out of bounds, returns `NONE`.

    Args:
        n (int): The index of the item to retrieve.

    Returns:
        Option[T]: `Some(item)` at the specified *n*.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter([10, 20]).nth(1)
        Some(20)
        >>> Iter([10, 20]).nth(3)
        NONE

        ```
    """
    try:
        return Some(next(itertools.islice(iter(self), n, n + 1)))
    except StopIteration:
        return NONE

partition(predicate)

Consumes the Iterator, creating two Vec from it.

The predicate passed to partition() can return true, or false.

partition returns a pair, all of the elements for which it returned True, and all of the elements for which it returned False.

Parameters:

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

Function to determine partition boundaries.

required

Returns:

Type Description
tuple[Vec[T], Vec[T]]

tuple[Vec[T], Vec[T]]: The resulting pair of collections

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3, 4, 5)).partition(lambda x: x % 2 == 0)
(Vec(2, 4), Vec(1, 3, 5))
Source code in src/pyochain/abc/_iterator.py
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def partition(self, predicate: Callable[[T], bool]) -> tuple[Vec[T], Vec[T]]:
    """Consumes the `Iterator`, creating two `Vec` from it.

    The predicate passed to `partition()` can return true, or false.

    `partition` returns a pair, all of the elements for which it returned `True`, and all of the elements for which it returned `False`.

    Args:
        predicate (Callable[[T], bool]): Function to determine partition boundaries.

    Returns:
        tuple[Vec[T], Vec[T]]: The resulting pair of collections

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3, 4, 5)).partition(lambda x: x % 2 == 0)
        (Vec(2, 4), Vec(1, 3, 5))

        ```
    """
    from .._vec import Vec

    first, second = tls.partition(iter(self), predicate)
    return Vec.from_ref(first), Vec.from_ref(second)

peekable(n)

Retrieve the next n elements from the Iterator, whilst leaving the original iterator unconsumed.

The returned tuple contains two elements:

  • A Seq of the next n elements.
  • An Iter that includes the peeked elements followed by the remaining elements of the original Iterator.

Parameters:

Name Type Description Default
n int

Number of items to peek.

required

Returns:

Type Description
tuple[Seq[T], Self]

tuple[Seq[T], Self]: A tuple containing the peeked elements and the remaining iterator.

See Also

[Iter::cloned][cloned] to create an independent copy of the iterator.

Example
>>> from pyochain import Iter
>>> peeked, remaining = Iter((1, 2, 3)).peekable(2)
>>> peeked
Seq(1, 2)
>>> remaining.collect()
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
def peekable(self, n: int) -> tuple[Seq[T], Self]:
    """Retrieve the next **n** elements from the `Iterator`, whilst leaving the original iterator unconsumed.

    The returned tuple contains two elements:

    - A `Seq` of the next **n** elements.
    - An `Iter` that includes the peeked elements followed by the remaining elements of the original `Iterator`.

    Args:
        n (int): Number of items to peek.

    Returns:
        tuple[Seq[T], Self]: A tuple containing the peeked elements and the remaining iterator.

    See Also:
        [`Iter::cloned`][cloned] to create an independent copy of the iterator.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> peeked, remaining = Iter((1, 2, 3)).peekable(2)
        >>> peeked
        Seq(1, 2)
        >>> remaining.collect()
        Seq(1, 2, 3)

        ```
    """
    from .._seq import Seq

    iterator = iter(self)
    peeked = Seq(itertools.islice(iterator, n))
    remaining = self._from_iterable(itertools.chain(peeked, iterator))
    return peeked, remaining

reduce(func)

Apply a function of two arguments cumulatively to the items of an iterable, from left to right.

This effectively reduces the Iterator to a single value.

If initial is present, it is placed before the items of the Iterator in the calculation.

It then serves as a default when the Iterator is empty.

Parameters:

Name Type Description Default
func Callable[[T, T], T]

Function to apply cumulatively to the items of the iterable.

required

Returns:

Name Type Description
T T

Single value resulting from cumulative reduction.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).reduce(lambda a, b: a + b)
6
Source code in src/pyochain/abc/_iterator.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def reduce(self, func: Callable[[T, T], T]) -> T:
    """Apply a function of two arguments cumulatively to the items of an iterable, from left to right.

    This effectively reduces the `Iterator` to a single value.

    If initial is present, it is placed before the items of the `Iterator` in the calculation.

    It then serves as a default when the `Iterator` is empty.

    Args:
        func (Callable[[T, T], T]): Function to apply cumulatively to the items of the iterable.

    Returns:
        T: Single value resulting from cumulative reduction.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).reduce(lambda a, b: a + b)
        6

        ```
    """
    return functools.reduce(func, self)

skip(n)

Create an Iterator that skips the first n elements.

skip(n) skips elements until n elements are skipped or the end of the Iterator is reached (whichever happens first).

After that, all the remaining elements are yielded.

In particular, if the original Iterator is too short, then the returned Iterator is empty.

If n is negative or zero, the original Iterator is returned unchanged.

Parameters:

Name Type Description Default
n int

Number of elements to skip.

required

Returns:

Name Type Description
Self Self

An Iterator of the remaining elements.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).skip(1).collect()
Seq(2, 3)
>>> Iter((1, 2, 3)).skip(5).collect()
Seq()
>>> Iter((1, 2, 3)).skip(0).collect()
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
def skip(self, n: int) -> Self:
    """Create an `Iterator` that skips the first n elements.

    skip(**n**) skips elements until n elements are skipped or the end of the `Iterator` is reached (whichever happens first).

    After that, all the remaining elements are yielded.

    In particular, if the original `Iterator` is too short, then the returned `Iterator` is empty.

    If **n** is negative or zero, the original `Iterator` is returned unchanged.

    Args:
        n (int): Number of elements to skip.

    Returns:
        Self: An `Iterator` of the remaining elements.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).skip(1).collect()
        Seq(2, 3)
        >>> Iter((1, 2, 3)).skip(5).collect()
        Seq()
        >>> Iter((1, 2, 3)).skip(0).collect()
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), n, None))

skip_while(predicate)

Drop items while predicate holds.

Parameters:

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

Function to evaluate each item.

required

Returns:

Name Type Description
Self Self

An Iterator of the items after skipping those for which the predicate is true.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 0)).skip_while(lambda x: x > 0).collect()
Seq(0,)
Source code in src/pyochain/abc/_iterator.py
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
def skip_while(self, predicate: Callable[[T], bool]) -> Self:
    """Drop items while predicate holds.

    Args:
        predicate (Callable[[T], bool]): Function to evaluate each item.

    Returns:
        Self: An `Iterator` of the items after skipping those for which the predicate is true.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 0)).skip_while(lambda x: x > 0).collect()
        Seq(0,)

        ```
    """
    return self._from_iterable(itertools.dropwhile(predicate, iter(self)))

slice(start=None, stop=None, step=None)

Return a slice of the Iterator.

Parameters:

Name Type Description Default
start int | None

Starting index of the slice.

None
stop int | None

Ending index of the slice.

None
step int | None

Step size for the slice.

None

Returns:

Name Type Description
Self Self

An Iterator of the sliced items.

Example
>>> from pyochain import Iter
>>> data = (1, 2, 3, 4, 5)
>>> Iter(data).slice(1, 4).collect()
Seq(2, 3, 4)
>>> Iter(data).slice(step=2).collect()
Seq(1, 3, 5)
Source code in src/pyochain/abc/_iterator.py
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
def slice(
    self,
    start: int | None = None,
    stop: int | None = None,
    step: int | None = None,
) -> Self:
    """Return a slice of the `Iterator`.

    Args:
        start (int | None): Starting index of the slice.
        stop (int | None): Ending index of the slice.
        step (int | None): Step size for the slice.

    Returns:
        Self: An `Iterator` of the sliced items.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> data = (1, 2, 3, 4, 5)
        >>> Iter(data).slice(1, 4).collect()
        Seq(2, 3, 4)
        >>> Iter(data).slice(step=2).collect()
        Seq(1, 3, 5)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), start, stop, step))

sort(*, reverse=False)

Sort the elements of the Iterator.

The elements must support rich comparison operations (i.e., they must implement the necessary comparison dunder methods).

Note

This method must consume the entire Iterator to perform the sort.

The result is a new Vec over the sorted sequence.

Parameters:

Name Type Description Default
reverse bool

Whether to sort in descending order.

False

Returns:

Type Description
Vec[U]

Vec[U]: A Vec with elements sorted.

Example
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).sort()
Vec(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
def sort[U: SupportsRichComparison[Any]](
    self: PyoIterator[U], *, reverse: bool = False
) -> Vec[U]:
    """Sort the elements of the `Iterator`.

    The elements must support rich comparison operations (i.e., they must implement the necessary comparison dunder methods).

    Note:
        This method must consume the entire `Iterator` to perform the sort.

        The result is a new `Vec` over the sorted sequence.

    Args:
        reverse (bool): Whether to sort in descending order.

    Returns:
        Vec[U]: A `Vec` with elements sorted.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((3, 1, 2)).sort()
        Vec(1, 2, 3)

        ```
    """
    from .._vec import Vec

    return Vec.from_ref(sorted(iter(self), reverse=reverse))

sort_by(key, *, reverse=False)

Sort the elements of the sequence transformed by the key function.

Note

This method must consume the entire Iterator to perform the sort.

The result is a new Vec over the sorted sequence.

Parameters:

Name Type Description Default
key Callable[[T], SupportsRichComparison[Any]]

Function to extract a comparison key from each element.

required
reverse bool

Whether to sort in descending order.

False

Returns:

Type Description
Vec[T]

Vec[T]: A Vec with elements sorted.

Example
>>> from pyochain import Iter
>>> str_numbers = ("3", "1", "2")
>>> Iter(str_numbers).sort_by(int)
Vec('1', '2', '3')
>>> Iter(str_numbers).sort_by(int, reverse=True)
Vec('3', '2', '1')
>>> from dataclasses import dataclass
>>> @dataclass
... class Person:
...     name: str
...     age: int
>>>
>>> peoples = (
...     Person("Alice", 30),
...     Person("Bob", 25),
...     Person("Charlie", 35),
... )
>>> sorted_names = (
...     Iter(peoples)
...     .sort_by(lambda x: x.age)
...     .iter()
...     .map(lambda x: x.name)
...     .collect()
... )
>>> sorted_names
Seq('Bob', 'Alice', 'Charlie')
Source code in src/pyochain/abc/_iterator.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
def sort_by(
    self,
    key: Callable[[T], SupportsRichComparison[Any]],  # pyright: ignore[reportExplicitAny]
    *,
    reverse: bool = False,
) -> Vec[T]:
    """Sort the elements of the sequence transformed by the key function.

    Note:
        This method must consume the entire `Iterator` to perform the sort.

        The result is a new `Vec` over the sorted sequence.

    Args:
        key (Callable[[T], SupportsRichComparison[Any]]): Function to extract a comparison key from each element.
        reverse (bool): Whether to sort in descending order.

    Returns:
        Vec[T]: A `Vec` with elements sorted.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> str_numbers = ("3", "1", "2")
        >>> Iter(str_numbers).sort_by(int)
        Vec('1', '2', '3')
        >>> Iter(str_numbers).sort_by(int, reverse=True)
        Vec('3', '2', '1')
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        >>>
        >>> peoples = (
        ...     Person("Alice", 30),
        ...     Person("Bob", 25),
        ...     Person("Charlie", 35),
        ... )
        >>> sorted_names = (
        ...     Iter(peoples)
        ...     .sort_by(lambda x: x.age)
        ...     .iter()
        ...     .map(lambda x: x.name)
        ...     .collect()
        ... )
        >>> sorted_names
        Seq('Bob', 'Alice', 'Charlie')

        ```
    """
    from .._vec import Vec

    return Vec.from_ref(sorted(iter(self), reverse=reverse, key=key))

step_by(step)

Creates an Iterator starting at the same point, but stepping by the given step at each iteration.

Note

The first element of the iterator will always be returned, regardless of the step given.

Parameters:

Name Type Description Default
step int

Step size for selecting items.

required

Returns:

Name Type Description
Self Self

An Iterator of every nth item.

Example
>>> from pyochain import Iter
>>> Iter([0, 1, 2, 3, 4, 5]).step_by(2).collect()
Seq(0, 2, 4)
Source code in src/pyochain/abc/_iterator.py
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
def step_by(self, step: int) -> Self:
    """Creates an `Iterator` starting at the same point, but stepping by the given **step** at each iteration.

    Note:
        The first element of the iterator will always be returned, regardless of the **step** given.

    Args:
        step (int): Step size for selecting items.

    Returns:
        Self: An `Iterator` of every nth item.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter([0, 1, 2, 3, 4, 5]).step_by(2).collect()
        Seq(0, 2, 4)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), 0, None, step))

sum(start=0)

sum(start: int = 0) -> int
sum(start: int = 0) -> int
sum() -> T1 | Literal[0]
sum(start: A2) -> A1 | A2

Return the sum of the Iterator.

If the Iterator is empty (i.e., yields no elements), return the value of start (which defaults to 0).

Parameters:

Name Type Description Default
start int | T1 | A2

The value to return if the Iterator is empty.

0

Returns:

Type Description
int | T1 | A1 | A2

int | T1 | A1 | A2: The sum of all elements.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).sum()
6
>>> Iter(()).sum()
0
>>> Iter(()).sum(10)
10
Source code in src/pyochain/abc/_iterator.py
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
def sum[T1: SupportsSumWithNoDefaultGiven, A1: SupportsAnyAdd, A2: SupportsAnyAdd](
    self: PyoIterator[bool | LiteralInteger] | PyoIterator[T1] | PyoIterator[A1],
    start: int | T1 | A2 = 0,
) -> int | T1 | A1 | A2:
    """Return the sum of the `Iterator`.

    If the `Iterator` is empty (i.e., yields no elements), return the value of `start` (which defaults to `0`).

    Args:
        start (int | T1 | A2): The value to return if the `Iterator` is empty.

    Returns:
        int | T1 | A1 | A2: The sum of all elements.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 3)).sum()
        6
        >>> Iter(()).sum()
        0
        >>> Iter(()).sum(10)
        10

        ```
    """
    return sum(iter(self), start)

tail(n)

Return a Deque of the last n elements of the Iterator.

Parameters:

Name Type Description Default
n int

Number of elements to return.

required

Returns:

Type Description
Deque[T]

Deque[T]: A Deque containing the last n elements.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).tail(2)
Deque([2, 3], maxlen=2)
Source code in src/pyochain/abc/_iterator.py
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
def tail(self, n: int) -> Deque[T]:
    """Return a `Deque` of the last **n** elements of the `Iterator`.

    Args:
        n (int): Number of elements to return.

    Returns:
        Deque[T]: A `Deque` containing the last **n** elements.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).tail(2)
        Deque([2, 3], maxlen=2)

        ```
    """
    from collections import deque

    from ..collections import Deque

    # TODO: we should move this to Rust and make it fully lazy.
    return Deque.from_ref(deque(iter(self), n))

take(n)

Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner.

Iter.take(n) yields elements until n elements are yielded or the end of the iterator is reached (whichever happens first).

The returned iterator is either:

  • A prefix of length n if the original iterator contains at least n elements
  • All of the (fewer than n) elements of the original iterator if it contains fewer than n elements.

Parameters:

Name Type Description Default
n int

Number of elements to take.

required

Returns:

Name Type Description
Self Self

An Iterator of the first n items.

Example
>>> from pyochain import Iter
>>> data = (1, 2, 3)
>>> Iter(data).take(2).collect()
Seq(1, 2)
>>> Iter(data).take(5).collect()
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
def take(self, n: int) -> Self:
    """Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner.

    `Iter.take(n)` yields elements until n elements are yielded or the end of the iterator is reached (whichever happens first).

    The returned iterator is either:

    - A prefix of length n if the original iterator contains at least n elements
    - All of the (fewer than n) elements of the original iterator if it contains fewer than n elements.

    Args:
        n (int): Number of elements to take.

    Returns:
        Self: An `Iterator` of the first n items.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> data = (1, 2, 3)
        >>> Iter(data).take(2).collect()
        Seq(1, 2)
        >>> Iter(data).take(5).collect()
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), n))

take_while(predicate)

Take items while predicate holds.

Parameters:

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

Function to evaluate each item.

required

Returns:

Name Type Description
Self Self

An Iterator of the items taken while the predicate is true.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 0)).take_while(lambda x: x > 0).collect()
Seq(1, 2)
Source code in src/pyochain/abc/_iterator.py
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
def take_while(self, predicate: Callable[[T], bool]) -> Self:
    """Take items while predicate holds.

    Args:
        predicate (Callable[[T], bool]): Function to evaluate each item.

    Returns:
        Self: An `Iterator` of the items taken while the predicate is true.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 0)).take_while(lambda x: x > 0).collect()
        Seq(1, 2)

        ```
    """
    return self._from_iterable(itertools.takewhile(predicate, iter(self)))

try_collect()

try_collect() -> Option[Vec[U]]
try_collect() -> Option[Vec[U]]

Fallibly transforms self into a Vec, short circuiting if a failure is encountered.

try_collect() is a variation of collect() that allows fallible conversions during collection.

Its main use case is simplifying conversions from iterators yielding Option[T] or Result[T, E] into Option[Vec[T]].

Also, if a failure is encountered during try_collect(), the Iter is still valid and may continue to be used, in which case it will continue iterating starting after the element that triggered the failure.

See the last example below for an example of how this works.

Note

This method return Vec[U] instead of being customizable, because the underlying data structure must be mutable in order to build up the collection.

Returns:

Type Description
Option[Vec[U]]

Option[Vec[U]]: Some[Vec[U]] if all elements were successfully collected, or NONE if a failure was encountered.

Example
>>> from pyochain import Iter, Some, Ok, Err, NONE, Vec
>>> # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
>>> Iter((Some(1), Some(2), Some(3))).try_collect()
Some(Vec(1, 2, 3))
>>> # Failing to collect in the same way:
>>> Iter((Some(1), Some(2), NONE, Some(3))).try_collect()
NONE
>>> # A similar example, but with Result:
>>> Iter((Ok(1), Ok(2), Ok(3))).try_collect()
Some(Vec(1, 2, 3))
>>> Iter((Ok(1), Err("error"), Ok(3))).try_collect()
NONE
>>> def external_fn(x: int) -> Option[int]:
...     if x % 2 == 0:
...         return Some(x)
...     return NONE
>>>
>>> Iter((1, 2, 3, 4)).map(external_fn).try_collect()
NONE
>>> # Demonstrating that the iterator remains usable after a failure:
>>> it = Iter((Some(1), NONE, Some(3), Some(4)))
>>> it.try_collect()
NONE
>>> it.try_collect()
Some(Vec(3, 4))
Source code in src/pyochain/abc/_iterator.py
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
def try_collect[U](
    self: PyoIterator[Option[U]] | PyoIterator[Result[U, Any]],  # pyright: ignore[reportExplicitAny]
) -> Option[Vec[U]]:
    """Fallibly transforms **self** into a `Vec`, short circuiting if a failure is encountered.

    `try_collect()` is a variation of `collect()` that allows fallible conversions during collection.

    Its main use case is simplifying conversions from iterators yielding `Option[T]` or `Result[T, E]` into `Option[Vec[T]]`.

    Also, if a failure is encountered during `try_collect()`, the `Iter` is still valid and may continue to be used, in which case it will continue iterating starting after the element that triggered the failure.

    See the last example below for an example of how this works.

    Note:
        This method return `Vec[U]` instead of being customizable, because the underlying data structure must be mutable in order to build up the collection.

    Returns:
        Option[Vec[U]]: `Some[Vec[U]]` if all elements were successfully collected, or `NONE` if a failure was encountered.

    Example:
        ```python
        >>> from pyochain import Iter, Some, Ok, Err, NONE, Vec
        >>> # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
        >>> Iter((Some(1), Some(2), Some(3))).try_collect()
        Some(Vec(1, 2, 3))
        >>> # Failing to collect in the same way:
        >>> Iter((Some(1), Some(2), NONE, Some(3))).try_collect()
        NONE
        >>> # A similar example, but with Result:
        >>> Iter((Ok(1), Ok(2), Ok(3))).try_collect()
        Some(Vec(1, 2, 3))
        >>> Iter((Ok(1), Err("error"), Ok(3))).try_collect()
        NONE
        >>> def external_fn(x: int) -> Option[int]:
        ...     if x % 2 == 0:
        ...         return Some(x)
        ...     return NONE
        >>>
        >>> Iter((1, 2, 3, 4)).map(external_fn).try_collect()
        NONE
        >>> # Demonstrating that the iterator remains usable after a failure:
        >>> it = Iter((Some(1), NONE, Some(3), Some(4)))
        >>> it.try_collect()
        NONE
        >>> it.try_collect()
        Some(Vec(3, 4))

        ```
    """
    from .._vec import Vec

    return tls.try_collect(iter(self)).map(Vec.from_ref)

try_find(predicate)

Applies a function returning Result[bool, E] to find first matching element.

Short-circuits: stops at the first successful True or on the first error.

Parameters:

Name Type Description Default
predicate Callable[[T], Result[bool, E]]

Function returning a Result[bool, E].

required

Returns:

Type Description
Result[Option[T], E]

Result[Option[T], E]: The first matching element, or the first error.

Example
>>> from pyochain import Ok, Result, Err, Range
>>> def is_even(x: int) -> Result[bool, str]:
...     return Ok(x % 2 == 0) if x >= 0 else Err("negative number")
>>>
>>> Range(1, 6).iter().try_find(is_even)
Ok(Some(2))
Source code in src/pyochain/abc/_iterator.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
def try_find[E](
    self, predicate: Callable[[T], Result[bool, E]]
) -> Result[Option[T], E]:
    """Applies a function returning `Result[bool, E]` to find first matching element.

    Short-circuits: stops at the first successful `True` or on the first error.

    Args:
        predicate (Callable[[T], Result[bool, E]]): Function returning a `Result[bool, E]`.

    Returns:
        Result[Option[T], E]: The first matching element, or the first error.

    Example:
        ```python
        >>> from pyochain import Ok, Result, Err, Range
        >>> def is_even(x: int) -> Result[bool, str]:
        ...     return Ok(x % 2 == 0) if x >= 0 else Err("negative number")
        >>>
        >>> Range(1, 6).iter().try_find(is_even)
        Ok(Some(2))

        ```
    """
    return tls.try_find(iter(self), predicate)

try_fold(init, func)

Folds every element into an accumulator, short-circuiting on error.

Applies func cumulatively to items and the accumulator.

If func returns an error, stops and returns that error.

Parameters:

Name Type Description Default
init B

Initial accumulator value.

required
func Callable[[B, T], Result[B, E]]

Function that takes the accumulator and element, returns a Result[B, E].

required

Returns:

Type Description
Result[B, E]

Result[B, E]: Final accumulator or the first error.

Example
>>> from pyochain import Iter, Ok, Err, Result
>>> def checked_add(acc: int, x: int) -> Result[int, str]:
...     new_val = acc + x
...     if new_val > 100:
...         return Err("overflow")
...     return Ok(new_val)
>>>
>>> Iter((1, 2, 3)).try_fold(0, checked_add)
Ok(6)
>>> Iter([50, 40, 20]).try_fold(0, checked_add)
Err('overflow')
>>> Iter(()).try_fold(0, checked_add)
Ok(0)
Source code in src/pyochain/abc/_iterator.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def try_fold[B, E](
    self, init: B, func: Callable[[B, T], Result[B, E]]
) -> Result[B, E]:
    """Folds every element into an accumulator, short-circuiting on error.

    Applies **func** cumulatively to items and the accumulator.

    If **func** returns an error, stops and returns that error.

    Args:
        init (B): Initial accumulator value.
        func (Callable[[B, T], Result[B, E]]): Function that takes the accumulator and element, returns a `Result[B, E]`.

    Returns:
        Result[B, E]: Final accumulator or the first error.

    Example:
        ```python
        >>> from pyochain import Iter, Ok, Err, Result
        >>> def checked_add(acc: int, x: int) -> Result[int, str]:
        ...     new_val = acc + x
        ...     if new_val > 100:
        ...         return Err("overflow")
        ...     return Ok(new_val)
        >>>
        >>> Iter((1, 2, 3)).try_fold(0, checked_add)
        Ok(6)
        >>> Iter([50, 40, 20]).try_fold(0, checked_add)
        Err('overflow')
        >>> Iter(()).try_fold(0, checked_add)
        Ok(0)

        ```
    """
    return tls.try_fold(iter(self), init, func)

try_for_each(f)

Applies a fallible function to each item in the Iterator, stopping at the first error and returning that error.

This can also be thought of as the fallible form of .for_each().

Parameters:

Name Type Description Default
f Callable[[T], Result[Any, E]]

A function that takes an item of type T and returns a Result.

required

Returns:

Type Description
Result[tuple[], E]

Result[tuple[()], E]: Returns Ok(()) if all applications of f were successful (i.e., returned Ok), or the first error E encountered.

Example
>>> from pyochain import Iter, Result, Ok, Err
>>> def validate_positive(n: int) -> Result[tuple[()], str]:
...     if n > 0:
...         return Ok("success")
...     return Err(f"Value {n} is not positive")
>>>
>>> Iter((1, 2, 3, 4, 5)).try_for_each(validate_positive)
Ok(())
>>> # Short-circuit on first error:
>>> Iter((1, 2, -1, 4)).try_for_each(validate_positive)
Err('Value -1 is not positive')
Source code in src/pyochain/abc/_iterator.py
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
def try_for_each[E](self, f: Callable[[T], Result[Any, E]]) -> Result[tuple[()], E]:  # pyright: ignore[reportExplicitAny]
    """Applies a fallible function to each item in the `Iterator`, stopping at the first error and returning that error.

    This can also be thought of as the fallible form of `.for_each()`.

    Args:
        f (Callable[[T], Result[Any, E]]): A function that takes an item of type `T` and returns a `Result`.

    Returns:
        Result[tuple[()], E]: Returns `Ok(())` if all applications of **f** were successful (i.e., returned `Ok`), or the first error `E` encountered.

    Example:
        ```python
        >>> from pyochain import Iter, Result, Ok, Err
        >>> def validate_positive(n: int) -> Result[tuple[()], str]:
        ...     if n > 0:
        ...         return Ok("success")
        ...     return Err(f"Value {n} is not positive")
        >>>
        >>> Iter((1, 2, 3, 4, 5)).try_for_each(validate_positive)
        Ok(())
        >>> # Short-circuit on first error:
        >>> Iter((1, 2, -1, 4)).try_for_each(validate_positive)
        Err('Value -1 is not positive')

        ```
    """
    return tls.try_for_each(iter(self), f)

try_reduce(func)

Reduces elements to a single one, short-circuiting on error.

Uses the first element as the initial accumulator. If func returns an error, stops immediately.

Parameters:

Name Type Description Default
func Callable[[T, T], Result[T, E]]

Function that reduces two items, returns a Result[T, E].

required

Returns:

Type Description
Result[Option[T], E]

Result[Option[T], E]: Final accumulated value or the first error. Returns Ok(NONE) for empty iterable.

Example
>>> from pyochain import Iter, Ok, Err, Result
>>> def checked_add(x: int, y: int) -> Result[int, str]:
...     if x + y > 100:
...         return Err("overflow")
...     return Ok(x + y)
>>>
>>> Iter((1, 2, 3)).try_reduce(checked_add)
Ok(Some(6))
>>> Iter([50, 60]).try_reduce(checked_add)
Err('overflow')
>>> Iter(()).try_reduce(checked_add)
Ok(NONE)
Source code in src/pyochain/abc/_iterator.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
def try_reduce[E](
    self, func: Callable[[T, T], Result[T, E]]
) -> Result[Option[T], E]:
    """Reduces elements to a single one, short-circuiting on error.

    Uses the first element as the initial accumulator. If **func** returns an error, stops immediately.

    Args:
        func (Callable[[T, T], Result[T, E]]): Function that reduces two items, returns a `Result[T, E]`.

    Returns:
        Result[Option[T], E]: Final accumulated value or the first error. Returns `Ok(NONE)` for empty iterable.

    Example:
        ```python
        >>> from pyochain import Iter, Ok, Err, Result
        >>> def checked_add(x: int, y: int) -> Result[int, str]:
        ...     if x + y > 100:
        ...         return Err("overflow")
        ...     return Ok(x + y)
        >>>
        >>> Iter((1, 2, 3)).try_reduce(checked_add)
        Ok(Some(6))
        >>> Iter([50, 60]).try_reduce(checked_add)
        Err('overflow')
        >>> Iter(()).try_reduce(checked_add)
        Ok(NONE)

        ```
    """
    return tls.try_reduce(iter(self), func)

unique()

Return only unique elements of the iterable.

Returns:

Name Type Description
Self Self

An Iterator of the unique items.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).unique().collect()
Seq(1, 2, 3)
>>> Iter([1, 2, 1, 3]).unique().collect()
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
def unique(self) -> Self:
    """Return only unique elements of the iterable.

    Returns:
        Self: An `Iterator` of the unique items.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).unique().collect()
        Seq(1, 2, 3)
        >>> Iter([1, 2, 1, 3]).unique().collect()
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(tls.UniqueIdentity(iter(self)))

unique_by(key)

Return only unique elements of the iterable.

Parameters:

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

Function to transform items before comparison.

required

Returns:

Name Type Description
Self Self

An Iterator of the unique items.

Example
>>> from pyochain import Iter
>>> Iter(["cat", "mouse", "dog", "hen"]).unique_by(key=len).collect()
Seq('cat', 'mouse')
Source code in src/pyochain/abc/_iterator.py
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
def unique_by(self, key: Callable[[T], Any]) -> Self:  # pyright: ignore[reportExplicitAny]
    """Return only unique elements of the iterable.

    Args:
        key (Callable[[T], Any]): Function to transform items before comparison.

    Returns:
        Self: An `Iterator` of the unique items.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter(["cat", "mouse", "dog", "hen"]).unique_by(key=len).collect()
        Seq('cat', 'mouse')

        ```
    """
    return self._from_iterable(tls.UniqueKey(iter(self), key=key))

unpack_into(func, *args, **kwargs)

Unpack the Iterator in the provided func, and return the result.

This is similar to Pipeable::into, but instead of passing Self, we pass the elements inside Self.

This avoids you to do iterator.into(lambda x: (*x)), improving performance and readability.

Note

This method will consume the Iterator.

Parameters:

Name Type Description Default
func Callable[Concatenate[T, P], R]

Function to call with the unpacked elements of the Iterator.

required
*args P.args

Additional positional arguments to pass to func

()
**kwargs P.kwargs

Additional keyword arguments to pass to func

{}

Returns:

Name Type Description
R R

The result of calling func with the unpacked elements of the Iterator and any additional arguments.

Example
>>> from pyochain import Seq

>>> data = Seq((1, 2, 3))
>>> def foo(*a: int, x: str) -> str:
...     return x + str(sum(a))
>>> data.iter().unpack_into(foo, x="Result: ")
'Result: 6'
>>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
>>> data.iter().unpack_into(lambda a, b, c: a + b + c)
6
Source code in src/pyochain/abc/_iterator.py
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
def unpack_into[**P, R](
    self,
    func: Callable[Concatenate[T, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> R:
    """Unpack the `Iterator` in the provided *func*, and return the result.

    This is similar to `Pipeable::into`, but instead of passing `Self`, we pass the elements inside `Self`.

    This avoids you to do `iterator.into(lambda x: (*x))`, improving performance and readability.

    Note:
        This method will consume the `Iterator`.

    Args:
        func (Callable[Concatenate[T, P], R]): Function to call with the unpacked elements of the `Iterator`.
        *args (P.args): Additional positional arguments to pass to *func*
        **kwargs (P.kwargs): Additional keyword arguments to pass to *func*

    Returns:
        R: The result of calling *func* with the unpacked elements of the `Iterator` and any additional arguments.

    Example:
        ```python
        >>> from pyochain import Seq

        >>> data = Seq((1, 2, 3))
        >>> def foo(*a: int, x: str) -> str:
        ...     return x + str(sum(a))
        >>> data.iter().unpack_into(foo, x="Result: ")
        'Result: 6'
        >>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
        >>> data.iter().unpack_into(lambda a, b, c: a + b + c)
        6

        ```
    """
    return func(*iter(self), *args, **kwargs)