Skip to content

PyoIterator

Bases: PyoIterable[T], Protocol


              flowchart TD
              pyochain.abc._iterator.PyoIterator[PyoIterator]
              pyochain.abc._iterable.PyoIterable[PyoIterable]
              pyochain.abc._mixins.Checkable[Checkable]
              pyochain.abc._mixins.Fluent[Fluent]
              pyochain.abc._mixins.Pipe[Pipe]
              pyochain.abc._mixins.Tap[Tap]

                              pyochain.abc._iterable.PyoIterable --> pyochain.abc._iterator.PyoIterator
                                pyochain.abc._mixins.Checkable --> pyochain.abc._iterable.PyoIterable
                
                pyochain.abc._mixins.Fluent --> pyochain.abc._iterable.PyoIterable
                                pyochain.abc._mixins.Pipe --> pyochain.abc._mixins.Fluent
                
                pyochain.abc._mixins.Tap --> pyochain.abc._mixins.Fluent
                




              click pyochain.abc._iterator.PyoIterator href "" "pyochain.abc._iterator.PyoIterator"
              click pyochain.abc._iterable.PyoIterable href "" "pyochain.abc._iterable.PyoIterable"
              click pyochain.abc._mixins.Checkable href "" "pyochain.abc._mixins.Checkable"
              click pyochain.abc._mixins.Fluent href "" "pyochain.abc._mixins.Fluent"
              click pyochain.abc._mixins.Pipe href "" "pyochain.abc._mixins.Pipe"
              click pyochain.abc._mixins.Tap href "" "pyochain.abc._mixins.Tap"
            

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 import Seq, Some
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)
assert counter.next() == Some(5)
assert counter.next() == Some(6)
assert counter.iter().take(3).collect(Seq) == Seq(7, 8, 9)
Source code in pyochain/abc/_iterator.pyi
  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
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
@runtime_checkable
class PyoIterator[T](PyoIterable[T], Protocol):
    """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 import Seq, Some
        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)
        assert counter.next() == Some(5)
        assert counter.next() == Some(6)
        assert counter.iter().take(3).collect(Seq) == Seq(7, 8, 9)
        ```
    """
    @abstractmethod
    def __next__(self) -> T: ...
    @override
    def __iter__(self) -> Iterator[T]: ...
    @classmethod
    def from_count(cls, start: int = 0, step: int = 1) -> PyoIterator[int]:
        """Create an `Iterator` of evenly spaced values, beginning with *start*.

        Can be used with `map()` to generate consecutive data points or with `zip()` to add sequence numbers.

        Warning:
            The `Iterator` returned is **infinite**, meaning it will never stop yielding elements.

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

            Otherwise you could quickly run out of memory, if you try to collect it into a collection.

        Args:
            start (int): Starting value of the `Iterator`.
            step (int): Difference between consecutive values.

        Returns:
            PyoIterator[int]: An `Iterator` of integers starting from **start** and increasing by **step**.

        Example:
            ```python
            from pyochain import Iter, Seq

            assert Iter.from_count(10, 2).take(3).collect(Seq) == Seq(10, 12, 14)
            assert Iter.from_count(-5, 5).take(4).collect(Seq) == Seq(-5, 0, 5, 10)
            assert Iter.from_count(0, -1).take(5).collect(Seq) == (0, -1, -2, -3, -4)
            x = Iter.from_count(0, 5).map(lambda x: x**2).take(4).collect(tuple)
            assert x == (0, 25, 100, 225)
            y = Iter.from_count(0, 5).zip([1, 2, 3]).collect(tuple)
            assert y == ((0, 1), (5, 2), (10, 3))
            ```
        """

    @classmethod
    def from_fn[**P, R](
        cls, f: Callable[P, Option[R]], *args: P.args, **kwargs: P.kwargs
    ) -> PyoIterator[R]:
        r"""Create an `Iterator` from a generator function.

        The `Callable` must return:

        - `Some(value)` to yield a value
        - `NONE` to stop the iteration

        You could consider this as a way to create an `Iterator` where the `__next__()` is the `__call__()` method.

        As such, you can either provide lambdas, partials, closures, or pre-existing classes where `__call__()` is implemented, but a `__next__()` is not desired.

        If you do have an `Iterator` class, simply pass it to the regular constructor, as this will be more efficient, ergonomic and idiomatic.

        Args:
            f (Callable[P, Option[R]]): `Callable` that returns the next item wrapped in `Option`.
            *args (P.args): Positional arguments to pass to **f**.
            **kwargs (P.kwargs): Keyword arguments to pass to **f**.

        Returns:
            PyoIterator[R]: An `Iterator` yielding values produced by **f**.

        Note:
            In Rust, this avoids defining a full struct and implementing `Iterator` for it when you have simple logic to generate values.

            This is implemented for "Rust API compliance", but in Python, generators comprehensions/functions with `yield` statements are the ergonomic equivalent.

        Example:
            Closure with captured local variable:
            ```python
            from pyochain import Iter, Some, NONE, Option

            def make_counter(max_val: int):
                counter = 0

                def gen() -> Option[int]:
                    nonlocal counter
                    counter += 1
                    return Some(counter) if counter <= max_val else NONE

                return gen

            x = Iter.from_fn(make_counter(5)).collect(tuple)
            assert x == (1, 2, 3, 4, 5)
            ```
            Reading records from a text stream:
            ```python
            from io import StringIO

            stream = StringIO("Alice\nBob\nCharlie\n")

            def read_name() -> Option[str]:
                line = stream.readline()
                return Some(line.rstrip("\n")) if line else NONE

            iterator = Iter.from_fn(read_name)
            assert iterator.next() == Some("Alice")
            assert iterator.next() == Some("Bob")
            assert iterator.next() == Some("Charlie")
            assert iterator.next().is_none()
            ```
        """

    @classmethod
    def once[V](cls, value: V) -> PyoIterator[V]:
        """Create an `Iterator` that yields a single value.

        It's a bit more performant compared to `Iter(value)`, since this bypass the runtime checks in its constructor.

        Args:
            value (V): The single value to yield.

        Returns:
            PyoIterator[V]: An `Iterator` yielding the specified value.

        Example:
            ```python
            from pyochain import Iter, Seq

            assert Iter.once(42).collect(Seq) == Seq(
                42,
            )
            ```
        """

    @classmethod
    def once_with[**P, R](
        cls, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
    ) -> PyoIterator[R]:
        """Create an `Iterator`  that lazily generates a value exactly once by invoking the provided closure.

        If you have a function which works on iterators, but you only need to process one value, you can use this method rather than doing something like `Iter([value])`.

        This can be considered the lazy counterpart of [`once`][].

        Args:
            func (Callable[P, R]): The single value to yield.
            *args (P.args): Positional arguments to pass to **func**.
            **kwargs (P.kwargs): Keyword arguments to pass to **func**.

        Returns:
            PyoIterator[R]: An `Iterator` yielding the specified value.

        Example:
            ```python
            from pyochain import Iter, Seq

            assert Iter.once_with(lambda: 42).collect(Seq) == Seq(
                42,
            )
            ```
        """

    @classmethod
    def repeat[O](cls, obj: O, n: int | None = None) -> PyoIterator[O]:
        """Repeat the provided object **n** times as elements of an `Iterator`.

        If **n** is `None`, this will create an infinite `Iterator`.

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

        Warning:
            Each repetition is a reference to the same object, not a copy.

            This means that if the object is mutable and you modify one of the repetitions, all next repetitions will reflect that change.

        Args:
            obj (O): The object to repeat.
            n (int | None): Optional number of repetitions.

        Returns:
            PyoIterator[O]: An `Iterator` of repeated **obj**.

        See Also:
            [`cycle`][] to repeat the **elements** of the `Iterator`.

        Example:
            ```python
            from pyochain import Seq, Iter

            assert Iter.repeat(1, 3).collect(Seq) == (1, 1, 1)
            assert Iter.repeat(("a", "b"), 2).collect(Seq) == (("a", "b"), ("a", "b"))
            ```
            A common use for repeat is to supply a stream of constant values to map or zip:
            ```python
            from pyochain import Range

            out = Range(10).iter().map_with(pow, Iter.repeat(2)).collect(Seq)
            assert out == (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
            ```

            Shared reference behavior:
            ```python
            from pyochain import Vec

            base = ["Alice", "Bob", "Charlie"]

            first, second = Iter.repeat(base).take(2).collect(tuple)
            first.append("Joe")

            assert first == ["Alice", "Bob", "Charlie", "Joe"]
            assert base == ["Alice", "Bob", "Charlie", "Joe"]
            assert second == ["Alice", "Bob", "Charlie", "Joe"]
            assert first is second and first is base and second is base
            ```
        """

    @classmethod
    def successors[U](
        cls, first: Option[U], succ: Callable[[U], Option[U]]
    ) -> PyoIterator[U]:
        """Create an iterator of successive values computed from the previous one.

        The iterator yields `first` (if it is `Some`), then repeatedly applies **succ** to the
        previous yielded value until it returns `NONE`.

        Args:
            first (Option[U]): Initial item.
            succ (Callable[[U], Option[U]]): Successor function.

        Returns:
            PyoIterator[U]: `Iterator` yielding `first` and its successors.

        Example:
            ```python
            from pyochain import Iter, Some, NONE, Option, Seq

            def next_pow10(x: int) -> Option[int]:
                return Some(x * 10) if x < 10_000 else NONE

            a = Iter.successors(Some(1), next_pow10).collect(Seq)
            assert a == (1, 10, 100, 1000, 10000)
            b = Iter.successors(NONE, next_pow10).collect(Seq)
            assert b == ()
            ```
        """

    @overload
    def accumulate[S](
        self: PyoIterator[S], func: None = None, initial: S | None = None
    ) -> PyoIterator[S]: ...
    @overload
    def accumulate[I, N](
        self: PyoIterator[N],
        func: Callable[[I, N], I],
        initial: I | None = None,
    ) -> PyoIterator[I]: ...
    def accumulate[S](
        self: PyoIterator[S],
        func: Callable[[S, S], S] | None = None,
        initial: S | None = None,
    ) -> PyoIterator[S]:
        """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.

        **function** should accept two arguments, an accumulated total and a value from the `Iterator`.

        Args:
            func (Callable[[S, S], S] | None): Optional binary function to apply cumulatively. If `None`, the default is to use addition (`operator.add`).
            initial (S | None): Optional initial value to start the accumulation.

        Returns:
            PyoIterator[S]: A new `Iterator` with accumulated results.

        Example:
            ```python
            import operator as op
            from pyochain import Seq

            s = Seq(1, 2, 3)
            assert s.iter().accumulate().collect(tuple) == (1, 3, 6)
            assert s.iter().accumulate(initial=10).collect(tuple) == (10, 11, 13, 16)
            assert s.iter().accumulate(op.mul).collect(tuple) == (1, 2, 6)
            assert s.iter().accumulate(op.add, 0).collect(Seq) == (0, 1, 3, 6)
            # The final accumulated result is the same as fold:
            assert s.iter().fold(0, op.add) == 6
            assert s.iter().accumulate(op.mul).collect(Seq) == (1, 2, 6)
            assert s.iter().accumulate().collect(Seq) == (1, 3, 6)
            ```
            To compute a running minimum, set function to `min()`.

            For a running maximum, set function to `max()`.

            Or for a running product, set function to `operator.mul()`.

            To build an amortization table, accumulate the interest and apply payments:
            ```python
            from pyochain import Iter
            import operator

            data = Seq(3, 4, 6, 2, 1, 9, 0, 7, 5, 8)
            running_max = data.iter().accumulate(max).collect(Seq)
            assert running_max == (3, 4, 6, 6, 6, 9, 9, 9, 9, 9)

            running_product = data.iter().accumulate(operator.mul).collect(Seq)
            assert running_product == (3, 12, 72, 144, 144, 1296, 0, 0, 0, 0)

            # Amortize a 5% loan of 1000 with 10 annual payments of 90
            update = lambda balance, payment: round(balance * 1.05) - payment
            res = Iter.repeat(90, 10).accumulate(update, initial=1_000).collect(list)
            assert res == [1000, 960, 918, 874, 828, 779, 728, 674, 618, 559, 497]
            ```
        """

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

        `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 `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 Seq

            assert Seq(1, True).iter().all()
            assert Seq().iter().all()
            assert not Seq(1, 0).iter().all()

            def is_even(x: int) -> bool:
                return x % 2 == 0

            assert Seq(2, 4, 6).iter().all(is_even)
            assert not Seq("a", "", "c").iter().all()
            assert not Seq(1, None, 3).iter().all()
            ```
        """

    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 Seq, Range

            assert Seq("AaaA").iter().all_equal(key=str.casefold)
            assert Range(9).iter().all_equal(key=lambda x: x < 10)
            assert not Range(9).iter().all_equal()
            ```
        """

    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 Seq, Set

            assert not Seq("ABCB").iter().all_unique()
            assert Seq("ABCb").iter().all_unique()

            # Alternative way to check uniqueness by comparing lengths:
            collection = Seq(1, 2, 3, 3)
            assert not collection.len() == collection.pipe(Set).len()
            ```
        """

    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 Seq

            assert Seq("ABCb").iter().all_unique()
            assert not Seq("ABCb").iter().all_unique_by(str.lower)
            ```
        """

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

        `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 `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 Seq, Range

            assert Seq(0, 1).iter().any()
            assert not Range(0).iter().any()

            def is_even(x: int) -> bool:
                return x % 2 == 0

            assert Seq(1, 3, 4).iter().any(is_even)
            ```
        """

    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

            assert Iter("abcdefghabcd").arg_max() == 7
            assert 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
            assert models.get(accuracy.iter().arg_max()).unwrap() == "knn"

            # Best accuracy
            assert accuracy.iter().max() == 84
            ```
        """

    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 Seq

            assert Seq("a", "bbb", "cc").iter().arg_max_by(len) == 1
            assert Seq("Alice", "bob", "charlie").iter().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
            assert models.get(accuracy.iter().arg_max_by(int)).unwrap() == "knn"

            # Best accuracy
            assert accuracy.iter().max_by(int) == "84"
            ```
        """

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

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

        Returns:
            int: The index of the minimum value.

        Example:
            ```python
            from pyochain import Seq

            assert Seq("efghabcdijkl").iter().arg_min() == 4
            assert Seq(3, 2, 1, 0, 4, 2, 1, 0).iter().arg_min() == 3
            ```
        """

    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 Seq

            assert Seq("aaa", "b", "cc").iter().arg_min_by(len) == 1
            assert Seq("Alice", "bob", "Charlie").iter().arg_min_by(str.lower) == 0
            ```
            Find the fastest healing family member based on age:
            ```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
            assert labels.get(ages.iter().arg_min_by(cost)).unwrap() == "bart"
            # Age with fastest healing
            assert ages.iter().min_by(key=cost) == 10
            ```
        """

    @overload
    def batched(
        self, n: Literal[1], *, strict: Literal[True]
    ) -> PyoIterator[tuple[T]]: ...
    @overload
    def batched(
        self, n: Literal[2], *, strict: Literal[True]
    ) -> PyoIterator[tuple[T, T]]: ...
    @overload
    def batched(
        self, n: Literal[3], *, strict: Literal[True]
    ) -> PyoIterator[tuple[T, T, T]]: ...
    @overload
    def batched(
        self, n: Literal[4], *, strict: Literal[True]
    ) -> PyoIterator[tuple[T, T, T, T]]: ...
    @overload
    def batched(
        self, n: Literal[5], *, strict: Literal[True]
    ) -> PyoIterator[tuple[T, T, T, T, T]]: ...
    @overload
    def batched(
        self, n: int, *, strict: Literal[False]
    ) -> PyoIterator[tuple[T, ...]]: ...
    @overload
    def batched(
        self, n: int, *, strict: bool = False
    ) -> PyoIterator[tuple[T, ...]]: ...
    def batched(self, n: int, *, strict: bool = False) -> PyoIterator[tuple[T, ...]]:
        """Batch elements into tuples of length n and return a new `Iterator`.

        - The last batch may be shorter than n.
        - The data is consumed lazily, just enough to fill a batch.
        - The result is yielded as soon as a batch is full or when the `Iterator` is exhausted.

        Note:
            This is the closest equivalent to `Iterator::array_chunks` in Rust.

        Args:
            n (int): Number of elements in each batch.
            strict (bool): If `True`, raises a ValueError if the last batch is not of length n.

        Returns:
            PyoIterator[tuple[T, ...]]: An iterable of batched tuples.

        Example:
            ```python
            from pyochain import Seq

            a = Seq("ABCDEFG").iter().batched(3).collect(Seq)
            b = (("A", "B", "C"), ("D", "E", "F"), ("G",))
            assert a == b
            data = Seq(1, 1, 2, -2, 6, 0, 3, 1, 0)
            #           ^-----^  ^------^  ^-----^
            assert data.iter().batched(3, strict=True).map(sum).all(lambda x: x == 4)
            ```
            You can use it to group elements into fixed-size groups.
            ```python
            from pyochain import Vec

            flattened_data = Vec("roses", "red", "violets", "blue", "sugar", "sweet")
            unflattened = flattened_data.iter().batched(2).collect(Vec)
            assert unflattened == [
                ("roses", "red"),
                ("violets", "blue"),
                ("sugar", "sweet"),
            ]
            ```
        """

    @overload
    def chain[S, O1](
        self: PyoIterator[S], o1: Iterable[O1], /
    ) -> PyoIterator[S | O1]: ...
    @overload
    def chain[S, O1, O2](
        self: PyoIterator[S], o1: Iterable[O1], o2: Iterable[O2], /
    ) -> PyoIterator[S | O1 | O2]: ...
    @overload
    def chain[S, O1, O2, O3](
        self: PyoIterator[S], o1: Iterable[O1], o2: Iterable[O2], o3: Iterable[O3], /
    ) -> PyoIterator[S | O1 | O2 | O3]: ...
    @overload
    def chain[S, O1, O2, O3, O4](
        self: PyoIterator[S],
        o1: Iterable[O1],
        o2: Iterable[O2],
        o3: Iterable[O3],
        o4: Iterable[O4],
        /,
    ) -> PyoIterator[S | O1 | O2 | O3 | O4]: ...
    @overload
    def chain[S, O1, O2, O3, O4, O5](
        self: PyoIterator[S],
        o1: Iterable[O1],
        o2: Iterable[O2],
        o3: Iterable[O3],
        o4: Iterable[O4],
        o5: Iterable[O5],
        /,
    ) -> PyoIterator[S | O1 | O2 | O3 | O4 | O5]: ...
    def chain[S, O](self: PyoIterator[S], *others: Iterable[O]) -> PyoIterator[S | O]:
        """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`.

        Tip:
            You can use `Iter.once()` with `chain()` for lazily prepending values to an already existing `Iterator`.

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

        Returns:
            PyoIterator[S | O]: 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 Seq, Iter, Range

            data = Seq(1, 2)
            # Multiple iterables of different types can be chained together:
            mixed = data.iter().chain((3, 4), [True], "hi").collect(Seq)
            assert mixed == (1, 2, 3, 4, True, "h", "i")
            # You can also chain infinite iterators,
            chained = (
                data
                .iter()
                .chain(Iter.from_count(3))
                .chain(Iter.from_count(2).map(lambda _: "unreachable"))
                .take(5)
                .collect(Seq)
            )
            assert chained == (1, 2, 3, 4, 5)
            ```
        """

    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 `Pipe::pipe` 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 [`Pipe::pipe`][Pipe.pipe] instead.

        Args:
            collector (Callable[[Iterator[T]], R]): Function|type that defines the target collection.

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

        Example:
            ```python
            from pyochain import Iter, Range, Vec, Dict

            data = Range(4)
            assert data.iter().collect(list) == [0, 1, 2, 3]
            assert data.iter().collect(Vec) == Vec(0, 1, 2, 3)
            assert data.iter().map(str).enumerate().collect(dict) == {
                0: "0",
                1: "1",
                2: "2",
                3: "3",
            }
            ```
            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(5)
                .iter()
                .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
                .collect(Seq[Result[int, int]])
            )
            assert data.pipe(repr) == "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.
        """

    @overload
    def collect_into[S](self: PyoIterator[S], collection: Vec[S]) -> Vec[S]: ...
    @overload
    def collect_into[S](
        self: PyoIterator[S], collection: PyoMutableSequence[S]
    ) -> PyoMutableSequence[S]: ...
    @overload
    def collect_into[S](self: PyoIterator[S], collection: list[S]) -> list[S]: ...
    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(2, 3)
            vec = Vec(1)
            b = a.iter().map(lambda x: x * 2).collect_into(vec)
            assert b == Vec(1, 4, 6)
            c = a.iter().map(lambda x: x * 10).collect_into(vec)
            assert c == Vec(1, 4, 6, 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()
            assert a.iter().collect_into(vec).len() == vec.len()
            assert a.iter().collect_into(vec).len() == vec.len()
            ```
        """

    @overload
    def combinations(self, r: Literal[2]) -> PyoIterator[tuple[T, T]]: ...
    @overload
    def combinations(self, r: Literal[3]) -> PyoIterator[tuple[T, T, T]]: ...
    @overload
    def combinations(self, r: Literal[4]) -> PyoIterator[tuple[T, T, T, T]]: ...
    @overload
    def combinations(self, r: Literal[5]) -> PyoIterator[tuple[T, T, T, T, T]]: ...
    def combinations(self, r: int) -> PyoIterator[tuple[T, ...]]:
        """Return an `Iterator` of `tuple` with **r** elements of type `T`.

        The output is a subsequence of `product()`, keeping only entries that are subsequences of the `Iterator`.

        The length of the output is given by `math.comb()` which computes the following:

        `n! / r! / (n - r)!` when `0 ≤ r ≤ n` or zero when `r > n`.

        The combination `tuples` are emitted in lexicographic order according to the order of the `Iterator`.

        If the latter is sorted, the output tuples will be produced in sorted order.

        Args:
            r (int): Length of each combination.

        Returns:
            PyoIterator[tuple[T, ...]]: An `Iterator` of combinations.

        Example:
            ```python
            from pyochain import Seq, Iter, Range

            a = Iter("ABCD").combinations(2).collect(Seq)
            assert a == (
                ("A", "B"),
                ("A", "C"),
                ("A", "D"),
                ("B", "C"),
                ("B", "D"),
                ("C", "D"),
            )
            b = Range(4).iter().combinations(3).collect(Seq)
            assert b == (
                (0, 1, 2),
                (0, 1, 3),
                (0, 2, 3),
                (1, 2, 3),
            )

            combined = Seq(1, 2, 3).iter().combinations(2).collect(Seq)
            assert combined == ((1, 2), (1, 3), (2, 3))
            ```
        """

    @overload
    def combinations_with_replacement(
        self, r: Literal[2]
    ) -> PyoIterator[tuple[T, T]]: ...
    @overload
    def combinations_with_replacement(
        self, r: Literal[3]
    ) -> PyoIterator[tuple[T, T, T]]: ...
    @overload
    def combinations_with_replacement(
        self,
        r: Literal[4],
    ) -> PyoIterator[tuple[T, T, T, T]]: ...
    @overload
    def combinations_with_replacement(
        self,
        r: Literal[5],
    ) -> PyoIterator[tuple[T, T, T, T, T]]: ...
    def combinations_with_replacement(self, r: int) -> PyoIterator[tuple[T, ...]]:
        """Return r length subsequences of elements from the `Iterator`, allowing individual elements to be repeated more than once.

        The output is a subsequence of `product()` that keeps only entries that are subsequences (with possible repeated elements) of the iterable.

        The number of subsequence returned is:

        `(n + r - 1)! / r! / (n - 1)!` when `n > 0`.

        The combination tuples are emitted in lexicographic order according to the order of the `Iterator`.

        If the `Iterator` is sorted, the output tuples will be produced in sorted order.

        Elements are treated as unique based on their position, not on their value.

        If the input elements are unique, the generated combinations will also be unique.

        Args:
            r (int): Length of each combination.

        Returns:
            PyoIterator[tuple[T, ...]]: An `Iterator` of combinations with replacement.

        Example:
            ```python
            from pyochain import Range, Seq, Iter

            a = Seq(1, 2, 3).iter().combinations_with_replacement(2).collect(Seq)
            assert a == ((1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3))
            b = Iter("ABC").combinations_with_replacement(2).collect(Seq)
            assert b == (
                ("A", "A"),
                ("A", "B"),
                ("A", "C"),
                ("B", "B"),
                ("B", "C"),
                ("C", "C"),
            )
            ```
        """

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

        Stops when either the `Iterator` or selectors iterables have been exhausted

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

        Returns:
            PyoIterator[T]: An `Iterator` of the items selected by the boolean selectors.

        Example:
            ```python
            from pyochain import Iter, Seq

            data = Seq("ABCDEF")
            selectors = (1, 0, 1, 0, 1, 1)
            expected = ("A", "C", "E", "F")
            a = data.iter().compress(*selectors).collect(Seq)
            assert a == expected
            # Roughly equivalent to:
            b = (
                data
                .iter()
                .zip(selectors)
                .filter_star(lambda _, selector: selector)
                .map_star(lambda x, _: x)
                .collect(Seq)
            )
            assert b == expected
            ```
        """

    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)
            assert data.count() == 3
            # data is now empty
            assert data.count() == 0
            ```
        """

    def cycle(self) -> PyoIterator[T]:
        """Yield elements from the `Iterator` endlessly, saving a copy of each call to `next()`.

        When the iterable is exhausted, return elements from the saved copy.

        Thus, instead of stopping once all the elements have been yielded, the iterator will instead start again, from the beginning.

        After iterating again, it will start at the beginning again. And again. And again. Forever.

        Note that in case the original iterator is empty, the resulting iterator will also be empty.

        You can use [`take`][] or [`slice`][] to limit the number of items taken.

        See Also:
            [`repeat`][] to create an `Iterator` from a single element repeatedly.

        Returns:
            PyoIterator[T]: A new `Iterator` that cycles through the elements indefinitely.

        Example:
            ```python
            from pyochain import Seq

            assert Seq(1, 2).iter().cycle().take(5).collect(Seq) == (1, 2, 1, 2, 1)
            assert Seq("ABC").iter().cycle().take(5).join("") == "ABCAB"
            ```
        """

    def enumerate(self, start: int = 0) -> PyoIterator[tuple[int, T]]:
        """Return a `Iterator` of (index, value) pairs.

        Each value in the `Iterator` is paired with its index, starting from 0.

        Tip:
            `map_star`[] can then be used for subsequent operations on the index and value.

            This keep the code clean and readable, without index access like `[0]` and `[1]` for inline lambdas.

        Args:
            start (int): The starting index.

        Returns:
            PyoIterator[tuple[int, T]]: An `Iterator` of (index, value) pairs.

        Example:
            ```python
            from pyochain import Seq

            data = Seq("apple", "banana", "cherry")
            output = data.iter().enumerate().collect(Seq)
            assert output == Seq((0, "apple"), (1, "banana"), (2, "cherry"))
            output = (
                data
                .iter()
                .enumerate()
                .map_star(lambda idx, val: (idx, val.upper()))
                .collect(Seq)
            )
            assert output == Seq((0, "APPLE"), (1, "BANANA"), (2, "CHERRY"))
            ```
        """

    def eq(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Range, Seq

            data = Range(1, 4)
            assert data.iter().eq((1, 2, 3)) and data.iter().eq(data)
            assert not data.iter().eq((1, 2, 4))
            assert not data.iter().eq((1, 2))
            ```
        """

    @overload
    def filter[N](self: PyoIterator[N | None], func: None = None) -> PyoIterator[N]: ...
    @overload
    def filter[R](self, func: Callable[[T], TypeIs[R]]) -> PyoIterator[R]: ...
    @overload
    def filter[R](self, func: Callable[[T], TypeGuard[R]]) -> PyoIterator[R]: ...
    @overload
    def filter(self, func: Callable[[T], object] | None) -> PyoIterator[T]: ...
    def filter[R, N](
        self, func: FilterFn[T, R] = None
    ) -> PyoIterator[T] | PyoIterator[R]:
        """Creates an `Iterator` with an optional closure to determine if an element should be yielded.

        Given an element the closure must return `True` or `False`.

        The returned `Iterator` will yield only the elements for which the closure returns `True`.

        If no closure is provided, the elements are directly evaluated on their truthiness.

        This means that empty collections, `0`, `False`, and `None` will be filtered out.

        The closure can return a `TypeIs` or `TypeGuard` to narrow the type of the returned `Iterator`.

        This won't have any runtime effect, but allows for better type inference.

        Note:
            `.filter(f).next()` is equivalent to [`.find(f)`][find].

        See Also:
            [`filter_false`][] for the complementary function that returns elements of the `Iterator` for which *func* is `False`.

        Args:
            func (FilterFn[T, R]): Function to evaluate each item.

        Returns:
            PyoIterator[T] | PyoIterator[R]: An `Iterator` of the items that satisfy the predicate.

        Example:
            ```python
            from pyochain import Iter, Seq, Some

            data = (1, 2, 3)
            assert Iter(data).filter(lambda x: x > 1).collect(Seq) == Seq(2, 3)
            # See the equivalence of next and find:
            assert Iter(data).filter(lambda x: x > 1).next() == Some(2)
            assert Iter(data).find(lambda x: x > 1) == Some(2)
            # Using TypeIs to narrow type:
            from typing import TypeIs

            def _is_str(x: object) -> TypeIs[str]:
                return isinstance(x, str)

            mixed_data = (1, "two", 3.0, "four")
            assert Iter(mixed_data).filter(_is_str).collect(Seq) == Seq("two", "four")
            maybe_none = (1, None, 3, None)
            assert Iter(maybe_none).filter().collect(Seq) == Seq(1, 3)
            maybe_false = (0, 1, False, 2, "", 3, None)
            assert Iter(maybe_false).filter().collect(Seq) == Seq(1, 2, 3)
            ```
        """

    @overload
    def filter_false[N](
        self: PyoIterator[N | None], func: None = None
    ) -> PyoIterator[None]: ...
    @overload
    def filter_false[U](self, func: Callable[[T], TypeIs[U]]) -> PyoIterator[U]: ...
    @overload
    def filter_false[U](self, func: Callable[[T], TypeGuard[U]]) -> PyoIterator[U]: ...
    @overload
    def filter_false(self, func: Callable[[T], object]) -> PyoIterator[T]: ...
    def filter_false[U](
        self, func: FilterFn[T, U] = None
    ) -> PyoIterator[T] | PyoIterator[U]:
        """Return elements for which **func** predicate is `False`.

        If no closure is provided, returns the elements who return `False` when calling `__bool__` on them.

        Args:
            func (FilterFn[T, U]): Function to evaluate each item.

        Returns:
            PyoIterator[T] | PyoIterator[U]: An `Iterator` of the items that do not satisfy the predicate.

        Example:
            ```python
            from pyochain import Seq, Range

            a = Range(5).iter().filter_false(lambda x: x > 1).collect(Seq)
            assert a == (0, 1)
            b = Seq(1, 4, 6, 3, 8).iter().filter_false(lambda x: x < 5).collect(Seq)
            assert b == Seq(6, 8)
            # Count number of none values
            assert Seq(1, None, 2, None, 3).iter().filter_false().count() == 2
            ```
        """

    def filter_map[R](self, func: Callable[[T], Option[R]]) -> PyoIterator[R]:
        """Creates an iterator that both filters and maps.

        The returned iterator yields only the values for which the supplied closure returns Some(value).

        `filter_map` can be used to make chains of `filter` and map more concise.

        The example below shows how a `map().filter().map()` can be shortened to a single call to `filter_map`.

        Args:
            func (Callable[[T], Option[R]]): Function to apply to each item.

        Returns:
            PyoIterator[R]: An iterable of the results where func returned `Some`.

        See Also:
            [`filter`][] with no closure provided if you want to filter out Python native `None` values.

        Example:
            ```python
            from pyochain import Result, Ok, Err, Seq

            def _parse(s: str) -> Result[int, str]:
                try:
                    return Ok(int(s))
                except ValueError:
                    return Err(f"Invalid integer, got {s!r}")

            data = Seq("1", "two", "NaN", "four", "5")
            parsed = data.iter().filter_map(lambda s: _parse(s).ok()).collect(Seq)
            assert parsed == Seq(1, 5)
            # Equivalent to:
            parsed = (
                data
                .iter()
                .map(lambda s: _parse(s).ok())
                .filter(lambda s: s.is_some())
                .map(lambda s: s.unwrap())
                .collect(Seq)
            )
            assert parsed == Seq(1, 5)
            ```
        """

    @overload
    def filter_map_star[R](
        self: PyoIterator[tuple[Any]],
        func: Callable[[Any], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, R](
        self: PyoIterator[tuple[T1, T2]],
        func: Callable[[T1, T2], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, R](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, R](
        self: PyoIterator[tuple[T1, T2, T3, T4]],
        func: Callable[[T1, T2, T3, T4], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5]],
        func: Callable[[T1, T2, T3, T4, T5], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, T6, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[[T1, T2, T3, T4, T5, T6], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, T6, T7, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], Option[R]],
    ) -> PyoIterator[R]: ...
    @overload
    def filter_map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], Option[R]],
    ) -> PyoIterator[R]: ...
    def filter_map_star[U: Iterable[Any], R](
        self: PyoIterator[U], func: Callable[..., Option[R]]
    ) -> PyoIterator[R]:
        """Creates an iterator that both filters and maps, where each element is an iterable.

        Unlike `.filter_map()`, which passes each element as a single argument, `.filter_map_star()` unpacks each element into positional arguments for the function.

        In short, for each `element` in the sequence, it computes `func(*element)`.

        This is useful after using methods like `zip`, `product`, or `enumerate` that yield tuples.

        Args:
            func (Callable[..., Option[R]]): Function to apply to unpacked elements.

        Returns:
            PyoIterator[R]: An iterable of the results where func returned `Some`.

        Example:
            ```python
            from pyochain import Result, Ok, Err, Seq

            data = Seq(("1", "10"), ("two", "20"), ("3", "thirty"))

            def _parse_pair(s1: str, s2: str) -> Result[tuple[int, int], str]:
                try:
                    return Ok((int(s1), int(s2)))
                except ValueError:
                    return Err(f"Invalid integer pair: {s1!r}, {s2!r}")

            parsed = (
                data
                .iter()
                .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
                .collect(list)
            )
            assert parsed == [(1, 10)]
            ```
        """

    @overload
    def filter_star[T1, R](
        self: PyoIterator[tuple[T1]], func: Callable[[T1], TypeIs[R]]
    ) -> PyoIterator[tuple[R]]: ...
    @overload
    def filter_star[T1, R](
        self: PyoIterator[tuple[T1]], func: Callable[[T1], TypeGuard[R]]
    ) -> PyoIterator[tuple[R]]: ...
    @overload
    def filter_star[T1](
        self: PyoIterator[tuple[T1]], func: Callable[[T1], object]
    ) -> PyoIterator[tuple[T1]]: ...
    @overload
    def filter_star[T1, T2, R, R2](
        self: PyoIterator[tuple[T1, T2]], func: Callable[[T1, T2], TypeIs[tuple[R, R2]]]
    ) -> PyoIterator[tuple[R, R2]]: ...
    @overload
    def filter_star[T1, T2, R, R2](
        self: PyoIterator[tuple[T1, T2]],
        func: Callable[[T1, T2], TypeGuard[tuple[R, R2]]],
    ) -> PyoIterator[tuple[R, R2]]: ...
    @overload
    def filter_star[T1, T2](
        self: PyoIterator[tuple[T1, T2]],
        func: Callable[[T1, T2], object],
    ) -> PyoIterator[tuple[T1, T2]]: ...
    @overload
    def filter_star[T1, T2, T3, R, R2, R3](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], TypeIs[tuple[R, R2, R3]]],
    ) -> PyoIterator[tuple[R, R2, R3]]: ...
    @overload
    def filter_star[T1, T2, T3, R, R2, R3](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], TypeGuard[tuple[R, R2, R3]]],
    ) -> PyoIterator[tuple[R, R2, R3]]: ...
    @overload
    def filter_star[T1, T2, T3](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], object],
    ) -> PyoIterator[tuple[T1, T2, T3]]: ...
    @overload
    def filter_star[T1, T2, T3, T4](
        self: PyoIterator[tuple[T1, T2, T3, T4]],
        func: Callable[[T1, T2, T3, T4], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5]],
        func: Callable[[T1, T2, T3, T4, T5], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5, T6](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[[T1, T2, T3, T4, T5, T6], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5, T6, T7](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5, T6, T7, T8](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5, T6, T7, T8, T9](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]]: ...
    @overload
    def filter_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], object],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]]: ...
    def filter_star[U: tuple[Any, ...]](
        self: PyoIterator[U], func: Callable[..., object]
    ) -> PyoIterator[U]:
        """Creates an `Iterator` which uses a closure **func** to determine if an element should be yielded, where each element is an iterable.

        Unlike `.filter()`, which passes each element as a single argument, `.filter_star()` unpacks each element into positional arguments for the **func**.

        In short, for each element in the `Iterator`, it computes `func(*element)``.

        This is useful after using methods like `.zip()`, `.product()`, or `.enumerate()` that yield tuples.

        Args:
            func (Callable[..., object]): Function to evaluate unpacked elements.

        Returns:
            PyoIterator[U]: An `Iterator` of the items that satisfy the predicate.

        Example:
            ```python
            from pyochain import Seq

            data = Seq("apple", "banana", "cherry", "date")
            output = (
                data
                .iter()
                .enumerate()
                .filter_star(lambda index, _: index % 2 == 0)
                .map_star(lambda _, fruit: fruit.title())
                .collect(Seq)
            )
            assert output == ("Apple", "Cherry")
            ```
        """

    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 Range, Some

            def gt_five(x: int) -> bool:
                return x > 5

            def gt_nine(x: int) -> bool:
                return x > 9

            data = Range(10)
            assert data.iter().find(predicate=gt_five) == Some(6)
            assert data.iter().find(predicate=gt_nine).unwrap_or("missing") == "missing"
            ```
        """

    def find_map[R](self, func: Callable[[T], Option[R]]) -> Option[R]:
        """Applies function to the elements of the `Iterator` and returns the first Some(R) result.

        `Iter.find_map(f)` is equivalent to `Iter.filter_map(f).next()`.

        Args:
            func (Callable[[T], Option[R]]): Function to apply to each element, returning an `Option[R]`.

        Returns:
            Option[R]: The first `Some(R)` result from applying `func`, or `NONE` if no such result is found.

        Example:
            ```python
            from pyochain import Seq, Some, NONE, Option

            def _parse(s: str) -> Option[int]:
                try:
                    return Some(int(s))
                except ValueError:
                    return NONE

            assert Seq("lol", "NaN", "2", "5").iter().find_map(_parse) == Some(2)
            ```
        """

    def flat_map[R](self, func: Callable[[T], Iterable[R]]) -> PyoIterator[R]:
        """Creates an iterator that applies a function to each element of the original iterator and flattens the result.

        This is useful when the **func** you want to pass to `.map()` itself returns an iterable, and you want to avoid having nested iterables in the output.

        This is equivalent to calling `.map(func).flatten()`.

        Args:
            func (Callable[[T], Iterable[R]]): Function to apply to each element.

        Returns:
            PyoIterator[R]: An iterable of flattened transformed elements.

        Example:
            ```python
            from pyochain import Range, Seq

            out = Range(1, 4).iter().flat_map(range).collect(Seq)
            assert out == Seq(0, 0, 1, 0, 1, 2)
            ```
        """
    # NOTE: I'm not sure if that's the best way to type this, but at least it allows to have a `Never` return type when the `Iterator` is not of `Iterable` type.
    # It clearly separates it from an `Unknown` return type, that may be shrugged off as a typing limitation, but in this case it is a clear indication that the `Iterator` is not of `Iterable` type and thus cannot be flattened.
    @overload
    def flatten[U](self: PyoIterator[Iterable[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten(self) -> Never: ...
    def flatten[U](self: PyoIterator[Iterable[U]]) -> PyoIterator[U]:
        """Creates an `Iterator` that flattens nested structures.

        This is useful when you have an `Iterator` of `Iterable` and you want to remove one level of indirection.

        Returns:
            PyoIterator[U]: An `Iterator` of flattened elements.

        Example:
            Basic usage:
            ```python
            from pyochain import Seq

            data = Seq((1, 2, 3, 4), (5, 6))
            flattened = data.iter().flatten().collect(Seq)
            assert flattened == Seq(1, 2, 3, 4, 5, 6)
            ```
            Mapping and then flattening:
            ```python
            words = Seq("he", "l", "lo!")
            merged = words.iter().flatten().collect(Seq)
            assert merged == Seq("h", "e", "l", "l", "o", "!")
            ```
            Flattening only removes one level of nesting at a time:
            ```python
            d3 = Seq(((1, 2), (3, 4)), ((5, 6), (7, 8)))
            d2 = d3.iter().flatten().collect(Seq)
            assert d2 == Seq((1, 2), (3, 4), (5, 6), (7, 8))
            d1 = d3.iter().flatten().flatten().collect(Seq)
            assert d1 == Seq(1, 2, 3, 4, 5, 6, 7, 8)
            ```
            Here we see that `flatten()` does not perform a “deep” flatten.

            Instead, only **one** level of nesting is removed.

            That is, if you `flatten()` a three-dimensional array, the result will be two-dimensional and not one-dimensional.

            To get a one-dimensional structure, you have to `flatten()` again.

        """

    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 Seq

            data = Seq(1, 2, 3)

            assert data.iter().fold(0, lambda acc, x: acc + x) == 6
            assert data.iter().fold(10, lambda acc, x: acc + x) == 16
            assert Seq("a", "b", "c").iter().fold("", lambda acc, x: acc + x) == "abc"
            ```
        """

    @overload
    def fold_star[**P, B](
        self: PyoIterator[tuple[Any]],
        init: B,
        func: Callable[[Any], B],
        *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 [`reduce`][] but with an initial value.

        Example:
            ```python
            from pyochain import Iter, Seq

            data = Seq((1, 2), (3, 4))
            assert data.iter().fold_star(0, lambda acc, x, y: acc + x + y) == 10
            data = Seq(("a", "b"), ("c", "d"))
            assert data.iter().fold_star("", lambda acc, x, y: acc + x + y) == "abcd"
            ```
            You can also pass additional arguments to the folding function:
            ```python
            data = Seq((1, 2), (3, 4))

            def add_with_offset(acc: int, x: int, y: int, offset: int) -> int:
                return acc + x + y + offset

            assert data.iter().fold_star(0, add_with_offset, 10) == 30
            ```
        """

    def for_each[**P](
        self,
        func: Callable[Concatenate[T, P], Any],
        *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 Range, Vec

            out = Vec()
            Range(1, 4).iter().for_each(out.append)
            assert out == Vec(1, 2, 3)
            ```
        """

    @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 Range, Vec

            vec = Vec()
            Range(1, 5).iter().batched(2).for_each_star(lambda x, y: vec.append(x + y))
            assert vec == Vec(3, 7)
            ```
        """

    def ge(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)

            assert data.iter().ge((1, 2))
            assert data.iter().ge(data)
            assert not data.iter().ge((1, 2, 4))
            ```
        """

    @overload
    def group_by(self, key: None = None) -> PyoIterator[tuple[T, PyoIterator[T]]]: ...
    @overload
    def group_by[K](
        self, key: Callable[[T], K]
    ) -> PyoIterator[tuple[K, PyoIterator[T]]]: ...
    @overload
    def group_by[K](
        self, key: Callable[[T], K] | None = None
    ) -> PyoIterator[tuple[K, PyoIterator[T]] | tuple[T, PyoIterator[T]]]: ...
    def group_by(
        self,
        key: Callable[[T], Any] | None = None,
    ) -> PyoIterator[tuple[Any | T, PyoIterator[T]]]:
        """Make an `Iterator` that returns consecutive keys and groups from the iterable.

        The values yielded are `(K, PyoIterator[T])` tuples, where the first element is the group key and the second element is an `Iterator` of type `T` over the group values.

        The `Iterator` needs to already be sorted on the same key function.

        This is due to the fact that it generates a new `Group` every time the value of the **key** function changes.

        That behavior differs from SQL's `GROUP BY` which aggregates common elements regardless of their input order.

        Warning:
            You must materialize the second element of the tuple immediately when iterating over groups.

            Because `.group_by()` uses Python's `itertools::groupby` under the hood, each group's iterator shares internal state.

            When you advance to the next group, the previous group's iterator becomes invalid and will yield empty results.

        Args:
            key (Callable[[T], Any] | None): Function computing a key value for each element. If `None`, this defaults to an identity function and returns the element unchanged.

        Returns:
            PyoIterator[tuple[Any | T, PyoIterator[T]]]: An `Iterator` of `(key, value)` tuples.

        Example:
            Simple usage:
            ```python
            from pyochain import Seq

            out = (
                Seq("AAAABBBCCDAABBB")
                .iter()
                .group_by()
                .map_star(lambda k, _: k)
                .collect(tuple)
            )
            assert out == ("A", "B", "C", "D", "A", "B")
            out = (
                Seq("AAAABBBCCD")
                .iter()
                .group_by()
                .map_star(lambda _, g: g.collect(list))
                .collect(tuple)
            )
            assert out == (
                ["A", "A", "A", "A"],
                ["B", "B", "B"],
                ["C", "C"],
                ["D"],
            )
            ```
            `group_by` can let you compute complex operations very easily and efficiently.

            For example, if we want to group even and odd numbers, we can do it like this:
            ```python
            from pyochain import Iter, Dict, Seq
            from operator import itemgetter

            # Example 1: Group even and odd numbers
            res = (
                Iter
                .from_count()  # create an infinite iterator of integers
                .take(8)  # take the first 8
                .map(lambda x: (x % 2 == 0, x))  # map to (is_even, value)
                .sort_by(itemgetter(0))  # sort by is_even
                .iter()  # Since sort collect to a Vec, we need to convert back to Iter
                .group_by(itemgetter(0))  # group by is_even
                # extract values from groups, discarding keys, and materializing them
                .map_star(
                    lambda g, vals: (g, vals.map_star(lambda _, y: y).collect(Seq))
                )
                .collect(Dict)
            )
            assert res == Dict({False: Seq(1, 3, 5, 7), True: Seq(0, 2, 4, 6)})
            ```
            If we have a dataset who's items have a common key and who's already sorted by that key, we can easily perform grouped operations on it, like this:
            ```python
            from pyochain import Seq

            data = Seq(
                {"name": "Alice", "gender": "F"},
                {"name": "Bob", "gender": "M"},
                {"name": "Charlie", "gender": "M"},
                {"name": "Dan", "gender": "M"},
            )
            # group by the gender key, and count the number of people in each group
            output = (
                data
                .iter()
                .group_by(lambda x: x["gender"])
                .map_star(lambda g, vals: (g, vals.count()))
                .collect(Seq)
            )
            assert output == (("F", 1), ("M", 3))
            ```
            However, you must be careful to materialize the group values immediately when iterating over groups, see below how the values of the groups are empty::
            ```python
            from pyochain import Seq

            groups = (
                Seq("a1", "a2", "b1")
                .iter()
                .group_by(lambda x: x[0])
                .collect(Seq)
                .iter()
                .map_star(lambda g, vals: (g, vals.collect(Seq)))
                .collect(Seq)
            )
            assert groups == (("a", Seq()), ("b", Seq()))
            ```
            As such, the correct pattern is the following:
            ```python
            from pyochain import Seq

            groups = (
                Seq("a1", "a2", "b1", "b2")
                .iter()
                .group_by(lambda x: x[0])
                # ✅ Materialize NOW
                .map_star(lambda g, vals: (g, vals.collect(Seq)))
                .collect(Seq)
            )
            assert groups == (("a", Seq("a1", "a2")), ("b", Seq("b1", "b2")))
            ```
        """

    def gt(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)
            assert data.iter().gt((1, 2))
            assert not data.iter().gt((1, 2, 9))
            assert not data.iter().gt((1, 2, 3))
            ```
        """

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

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

        Returns:
            PyoIterator[S]: A new `Iterator` with the element interposed.

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)
            # Simple example with numbers
            a = data.iter().intersperse(0).collect(Seq)
            assert a == Seq(1, 0, 2, 0, 3)
            # Useful when chaining with other operations
            assert data.iter().intersperse(5).sum() == 16
            # Inserting separators between groups, then flattening
            a = (
                Seq((1, 2), (3, 4), (5, 6))
                .iter()
                .intersperse([-1])
                .flatten()
                .collect(Seq)
            )
            assert a == Seq(1, 2, -1, 3, 4, -1, 5, 6)
            ```
        """

    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:
            [`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

            assert Iter(1, 2, 3, 4, 5).is_sorted()
            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 2)
            assert data.iter().is_sorted()
            assert not data.iter().is_sorted(strict=True)
            ```
        """

    def is_sorted_by(
        self,
        key: Callable[[T], SupportsComparison[Any]],
        *,
        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 Range, Seq

            assert Range(1, 6).iter().map(str).is_sorted_by(int)
            by_int = Seq(1, 5, 3).iter().map(str).is_sorted_by(int, reverse=True)
            assert not by_int
            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            from pyochain import Seq

            data = Seq("1", "2", "2")
            assert data.iter().is_sorted_by(int)
            assert not data.iter().is_sorted_by(int, strict=True)
            ```
        """

    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

            assert Iter("a", "b", "c").join("-") == "a-b-c"
            ```
        """

    def last(self) -> T:
        """Consume the `Iterator` and return it's last element.

        Warning:
            This will never return if the `Iterator` is infinite.

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

        Example:
            ```python
            from pyochain import Dict, Seq

            data = Dict(a=1, b=2, c=3)
            assert data.iter().last() == "c"
            # If you have a `Sequence`, you can use `PyoSequence::last` instead, which is more efficient.
            assert data.pipe(Seq).last() == "c"
            ```
        """

    def le(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)
            assert not data.iter().le((1, 2))
            assert data.iter().le((1, 2, 3))
            assert data.iter().le((1, 3))
            ```
        """

    def lt(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)
            assert not data.iter().lt((1, 2))
            assert not data.iter().lt((1, 2, 3))
            assert data.iter().lt((1, 3))
            ```
        """

    def map[R](self, func: Callable[[T], R]) -> PyoIterator[R]:
        """Apply a function **func** to each element of the `Iterator`.

        If you are good at thinking in types, you can think of `map` like this:

        - You have an `Iterator` that gives you elements of some type `A`
        - You want an `Iterator` of some other type `B`
        - Thenyou can use `.map()`, passing a closure **func** that takes an `A` and returns a `B`.

        `map` is conceptually similar to a for loop.

        However, as `map` is lazy, it is best used when you are already working with other `PyoIterator` instances.

        If you are doing some sort of looping for a side effect, it is considered more idiomatic to use [`for_each`][] than `map().collect(Seq)`.

        Args:
            func (Callable[[T], R]): Function to apply to each element.

        Returns:
            PyoIterator[R]: An iterator of transformed elements.

        Example:
            ```python
            from pyochain import Seq

            assert Seq(1, 2).iter().map(lambda x: x + 1).collect(Seq) == Seq(2, 3)
            # You can use methods on the class rather than on instance for convenience:
            data = Seq("a", "b", "c")

            a = data.iter().map(str.upper).collect(Seq)
            assert a == Seq("A", "B", "C")
            b = data.iter().map(lambda s: s.upper()).collect(Seq)
            assert b == Seq("A", "B", "C")
            ```
        """
    @overload
    def map_juxt[R1](self, func1: Callable[[T], R1], /) -> PyoIterator[tuple[R1]]: ...
    @overload
    def map_juxt[R1, R2](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        /,
    ) -> PyoIterator[tuple[R1, R2]]: ...
    @overload
    def map_juxt[R1, R2, R3](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5, R6](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        func6: Callable[[T], R6],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5, R6, R7](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        func6: Callable[[T], R6],
        func7: Callable[[T], R7],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5, R6, R7, R8](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        func6: Callable[[T], R6],
        func7: Callable[[T], R7],
        func8: Callable[[T], R8],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7, R8]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5, R6, R7, R8, R9](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        func6: Callable[[T], R6],
        func7: Callable[[T], R7],
        func8: Callable[[T], R8],
        func9: Callable[[T], R9],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7, R8, R9]]: ...
    @overload
    def map_juxt[R1, R2, R3, R4, R5, R6, R7, R8, R9, R10](
        self,
        func1: Callable[[T], R1],
        func2: Callable[[T], R2],
        func3: Callable[[T], R3],
        func4: Callable[[T], R4],
        func5: Callable[[T], R5],
        func6: Callable[[T], R6],
        func7: Callable[[T], R7],
        func8: Callable[[T], R8],
        func9: Callable[[T], R9],
        func10: Callable[[T], R10],
        /,
    ) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7, R8, R9, R10]]: ...
    @overload
    def map_juxt[R](self, *funcs: Callable[[T], R]) -> PyoIterator[tuple[R, ...]]: ...
    def map_juxt(self, *funcs: Callable[[T], Any]) -> PyoIterator[tuple[Any, ...]]:
        """Apply several functions to each item of the `Iterator`.

        Returns a new `Iterator` where each item is a tuple of the results of applying each function to the original item.

        This can be very handy to compute multiple transformations or properties of the same item in a single pass, without needing to iterate multiple times.

        As such, this can be considered as an alternative to various patterns, such as [`for_each`][] and [`fold`][] with mutable collections, or [`map`][] followed by [`zip`][] to combine the results.

        Args:
            *funcs (Callable[[T], Any]): Functions to apply to each item.

        Returns:
            PyoIterator[tuple[Any, ...]]: An `Iterator` of tuples containing the results of each function.

        Example:
            ```python
            from pyochain import Seq

            def is_even(n: int) -> bool:
                return n % 2 == 0

            def is_positive(n: int) -> bool:
                return n > 0

            out = Seq(1, -2, 3).iter().map_juxt(is_even, is_positive).collect(Seq)
            assert out == Seq((False, True), (True, False), (False, True))
            ```
            If you need to pass additional args and kwargs to the functions, you can use `functools::partial` or create curried functions like this:
            ```python
            from pyochain import Range
            from collections.abc import Callable

            def curried_add(a: int) -> Callable[[int], int]:
                def fn(b: int) -> int:
                    return a + b

                return fn

            out = (
                Range(1, 4)
                .iter()
                .map_juxt(curried_add(10), curried_add(20))
                .collect(Seq)
            )
            assert out == Seq((11, 21), (12, 22), (13, 23))
            ```
            You can then combine this with various other methods to perform complex transformations in a clean and efficient way, without needing to iterate multiple times or create intermediate collections.

            Example with `filter_star`:
            ```python
            res = (
                Range(5)
                .iter()
                .map_juxt(lambda x: x * 2, lambda x: x**2)
                .filter_star(lambda double, square: double + square <= 5)
                .collect(Seq)
            )
            assert res == Seq((0, 0), (2, 1))
            ```
        """

    @overload
    def map_star[T1, R](
        self: PyoIterator[tuple[T1]], func: Callable[[T1], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, R](
        self: PyoIterator[tuple[T1, T2]], func: Callable[[T1, T2], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, R](
        self: PyoIterator[tuple[T1, T2, T3]], func: Callable[[T1, T2, T3], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, R](
        self: PyoIterator[tuple[T1, T2, T3, T4]], func: Callable[[T1, T2, T3, T4], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5]],
        func: Callable[[T1, T2, T3, T4, T5], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[[T1, T2, T3, T4, T5, T6], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_star[U: tuple[Any, ...], R](
        self: PyoIterator[U], func: Callable[..., R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_star(self, func: Callable[..., Any]) -> Never: ...
    def map_star[R](
        self: PyoIterator[tuple[Any, ...]], func: Callable[..., R]
    ) -> PyoIterator[R]:
        """Applies a function to each element.where each element is a `tuple`.

        Unlike `.map()`, which passes each element as a single argument, `.map_star()` unpacks the tuple into positional arguments for the function.

        In short, for each element in the `Iterator`, it computes `func(*element)`.

        This is strictly equivalent to `itertools::starmap(func, self)`.

        Note:
            Always prefer using `.map_star()` over `.map()` when working with `Iterator` of `tuple` elements.

            Not only it is more readable, but it's also much more performant (up to 30% faster in benchmarks).

        Args:
            func (Callable[..., R]): Function to apply to unpacked elements.

        Returns:
            PyoIterator[R]: An `Iterator` of results from applying the function to unpacked elements.

        Example:
            ```python
            from pyochain import Seq

            def make_sku(color: str, size: str) -> str:
                return f"{color}-{size}"

            data = Seq("blue", "red")
            a = data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
            assert a == ("blue-S", "blue-M", "red-S", "red-M")
            # This is equivalent to:
            b = data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
            assert b == ("blue-S", "blue-M", "red-S", "red-M")
            ```
        """

    def map_while[R](self, func: Callable[[T], Option[R]]) -> PyoIterator[R]:
        """Creates an `Iterator` that both yields elements based on a predicate and maps.

        `map_while()` takes a closure *func* as an argument.

        It will call this closure on each element of the `Iterator`, and yield elements while it returns `Some(_)`.

        Args:
            func (Callable[[T], Option[R]]): Function to apply to each element`.

        Returns:
            PyoIterator[R]: An `Iterator` of transformed elements until `NONE` is encountered.

        Examples:
            Basic usage:
            ```python
            from pyochain import Vec, Some, NONE

            a = Vec(-1, 4, 0, 1)

            def checked_divide(x: int) -> Option[int]:
                if x == 0:
                    return NONE
                return Some(16 // x)

            iterator = a.iter().map_while(checked_divide)

            assert iterator.next() == Some(-16)
            assert iterator.next() == Some(4)
            assert iterator.next().is_none()
            ```
            Here's the same example, but with take_while and map:
            ```python
            a = Vec(-1, 4, 0, 1)

            iterator = (
                a
                .iter()
                .map(checked_divide)
                .take_while(lambda x: x.is_some())
                .map(lambda x: x.unwrap())
            )

            assert iterator.next() == Some(-16)
            assert iterator.next() == Some(4)
            assert iterator.next().is_none()
            ```
            Stopping after an initial None:
            ```python
            from pyochain import Result, Ok, Err

            a = Vec(0, 1, 2, -3, 4, 5, -6)

            def check_positive(x: int) -> Result[int, str]:
                if x < 0:
                    return Err("Negative value cannot be converted to u32")
                return Ok(x)

            iterator = a.iter().map_while(lambda x: check_positive(x).ok())
            vec = iterator.collect(Vec)

            # We have more elements that are positive (such as 4, 5),
            # but `map_while` returned `NONE` for `-3` (as the `predicate` returned `None`).
            assert vec == [0, 1, 2]
            ```
            Because map_while() needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:
            ```
            a = Vec(1, 2, -3, 4)
            iterator = a.iter()

            result = iterator.map_while(lambda n: u32_try_from(n).ok()).collect(Vec)

            assert result == [1, 2]

            result = iterator.collect(Vec)

            assert result == [4]
            ```

            The -3 is no longer there, because it was consumed in order to see if the iteration should stop, but wasn't placed back into the `Iterator`.
        """

    @overload
    def map_windows[R](
        self, length: Literal[1], func: Callable[[tuple[T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[2], func: Callable[[tuple[T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[3], func: Callable[[tuple[T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[4], func: Callable[[tuple[T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[5], func: Callable[[tuple[T, T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[6], func: Callable[[tuple[T, T, T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[7], func: Callable[[tuple[T, T, T, T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[8], func: Callable[[tuple[T, T, T, T, T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: Literal[9], func: Callable[[tuple[T, T, T, T, T, T, T, T, T]], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self,
        length: Literal[10],
        func: Callable[[tuple[T, T, T, T, T, T, T, T, T, T]], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows[R](
        self, length: int, func: Callable[[tuple[T, ...]], R]
    ) -> PyoIterator[R]: ...
    def map_windows[R](
        self,
        length: int,
        func: Callable[[tuple[Any, ...]], R],
    ) -> PyoIterator[R]:
        """Calls the given *func* for each contiguous window of size *length* over **self**.

        The windows during mapping overlaps.

        The provided function is called with the entire window as a single tuple argument.

        Args:
            length (int): The length of each window.
            func (Callable[[tuple[Any, ...]], R]): Function to apply to each window.

        Returns:
            PyoIterator[R]: An iterator over the outputs of func.

        See Also:
            [`map_windows_star`][] for a version that unpacks the window into separate arguments.

        Example:
            ```python
            from pyochain import Seq, Range
            import statistics

            data = Seq(1, 2, 3, 4)
            means = data.iter().map_windows(2, statistics.mean).collect(Seq)
            assert means == Seq(1.5, 2.5, 3.5)

            joined = (
                Seq("abcd")
                .iter()
                .map_windows(3, lambda window: "".join(window).upper())
                .collect(Seq)
            )
            assert joined == Seq("ABC", "BCD")

            sum_windows = Range(5).iter().map_windows(4, sum).collect(Seq)
            assert sum_windows == Seq(6, 10)
            ```
        """

    @overload
    def map_windows_star[R](
        self, length: Literal[1], func: Callable[[T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[2], func: Callable[[T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[3], func: Callable[[T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[4], func: Callable[[T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[5], func: Callable[[T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[6], func: Callable[[T, T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[7], func: Callable[[T, T, T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[8], func: Callable[[T, T, T, T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[9], func: Callable[[T, T, T, T, T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_windows_star[R](
        self, length: Literal[10], func: Callable[[T, T, T, T, T, T, T, T, T, T], R]
    ) -> PyoIterator[R]: ...
    def map_windows_star[R](
        self, length: int, func: Callable[..., R]
    ) -> PyoIterator[R]:
        """Calls the given *func* for each contiguous window of size *length* over **self**.

        The windows during mapping overlaps.

        The provided function is called with each element of the window as separate arguments.

        Args:
            length (int): The length of each window.
            func (Callable[..., R]): Function to apply to each window.

        Returns:
            PyoIterator[R]: An iterator over the outputs of func.

        See Also:
            [`map_windows`][] for a version that passes the entire window as a single tuple argument.

        Example:
            ```python
            from pyochain import Seq, Iter

            a = Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
            assert a == Seq("a+b", "b+c", "c+d")
            b = (
                Seq(1, 2, 3, 4)
                .iter()
                .map_windows_star(2, lambda x, y: x + y)
                .collect(Seq)
            )
            assert b == Seq(3, 5, 7)
            ```
        """

    @overload
    def map_with[T1, R](
        self, func: Callable[[T, T1], R], iterable: Iterable[T1], /
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, R](
        self,
        func: Callable[[T, T1, T2], R],
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        /,
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, R](
        self,
        func: Callable[[T, T1, T2, T3], R],
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        /,
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, T4, R](
        self,
        func: Callable[[T, T1, T2, T3, T4], R],
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, T4, T5, R](
        self,
        func: Callable[[T, T1, T2, T3, T4, T5], R],
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        /,
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, T4, T5, T6, R](
        self,
        func: Callable[[T, T1, T2, T3, T4, T5, T6], R],
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        /,
    ) -> PyoIterator[R]: ...
    def map_with[R](
        self, func: Callable[..., R], *iterables: Iterable[Any]
    ) -> PyoIterator[R]:
        """Applies a function to the elements of this `Iterator` and additional iterables.

        The provided function must take as many arguments as the number of iterables provided (including **self**).

        It is then applied to the items from all iterables in parallel.

        The `Iterator` stops when the shortest iterable is exhausted.

        Args:
            func (Callable[..., R]): Function to apply to the elements of the iterables.
            *iterables (Iterable[Any]): Additional iterables to zip with **self**.

        Returns:
            PyoIterator[R]: An `Iterator` of results from applying the function to the elements of the iterables.

        See Also:
            [`map_juxt`][] to apply multiple functions to the same elements of the `Iterator`.

        Example:
            ```python
            from pyochain import Seq
            from dataclasses import dataclass

            @dataclass
            class Triangle:
                x: int
                y: int
                z: int

            x = Seq(1, 2, 3)
            y = [4, 5, 6]
            z = [7, 8, 9]
            output = x.iter().map_with(Triangle, y, z).collect(Seq)
            assert output == Seq(
                Triangle(x=1, y=4, z=7),
                Triangle(x=2, y=5, z=8),
                Triangle(x=3, y=6, z=9),
            )
            output_2 = x.iter().map_with(lambda a, b, c: a + b + c, y, z).collect(Seq)
            assert output_2 == Seq(12, 15, 18)
            ```
        """

    def max[U: SupportsRichComparison](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`][] 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 Seq

            assert Seq(3, 1, 2).iter().max() == 3
            ```
        """

    def max_by[U: SupportsRichComparison](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)

            assert persons.iter().max_by(lambda p: p.age).name == "Alice"
            assert persons.iter().max_by(lambda p: p.name).name == "Charlie"
            assert persons.iter().max_by(Person.get_discount).name == "Bob"
            ```
        """

    def min[U: SupportsRichComparison](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 Seq

            assert Seq(3, 1, 2).iter().min() == 1
            ```
        """

    def min_by[U: SupportsRichComparison](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)

            assert persons.iter().min_by(lambda p: p.age).name == "Bob"
            assert persons.iter().min_by(lambda p: p.name).name == "Alice"
            assert persons.iter().min_by(Person.get_discount).name == "Alice"
            ```
        """

    def ne(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

        Example:
            ```python
            from pyochain import Range

            data = Range(1, 4)

            assert not data.iter().ne((1, 2, 3))
            assert data.iter().ne((1, 2, 4))
            assert data.iter().ne((1, 2))
            ```
        """

    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.

        `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, Some, Null

            it = Seq(1, 2, 3).iter()
            assert it.next() == Some(1)
            assert it.next() == Some(2)
            assert it.next() == Some(3)
            # iterator is now exhausted
            assert it.next() is Null()
            ```
        """

    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. It must be a non-negative integer.

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

        Example:
            ```python
            from pyochain import Range

            data = Range(10)
            assert data.iter().nth(1).unwrap() == 1
            assert data.iter().nth(10).is_none()
            ```
        """

    def pairwise(self) -> PyoIterator[tuple[T, T]]:
        """Return successive overlapping pairs from the `Iterator`.

        The number of 2-tuples in the resulting `Iterator` will be one fewer than the number of inputs.

        It will be empty if the current `Iterator` has fewer than two values.

        Returns:
            PyoIterator[tuple[T, T]]: An `Iterator` of pairs of consecutive elements.

        Example:
            ```python
            from pyochain import Seq

            assert Seq(1, 2, 3).iter().pairwise().collect(Seq) == ((1, 2), (2, 3))
            assert Seq("ABCDEFG").iter().pairwise().collect(Seq) == (
                ("A", "B"),
                ("B", "C"),
                ("C", "D"),
                ("D", "E"),
                ("E", "F"),
                ("F", "G"),
            )
            ```
        """

    def partition[S](
        self: PyoIterable[S], predicate: Callable[[S], bool]
    ) -> tuple[Vec[S], Vec[S]]:
        """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[[S], bool]): Function to determine partition boundaries.

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

        Example:
            ```python
            from pyochain import Vec, Range

            a, b = Range(1, 6).iter().partition(lambda x: x % 2 == 0)
            assert a == Vec(2, 4)
            assert b == Vec(1, 3, 5)
            ```
        """

    def peekable[S](self: PyoIterator[S]) -> Peekable[S]:
        """Creates an iterator which can use the peek and peek_mut methods to look at the next element of the `Iterator` without consuming it.

        See their documentation for more information.

        Note that the underlying `Iterator` is still advanced when peek or peek_mut are called for the first time.

        In order to retrieve the next element, `next` is called on the underlying `Iterator`, hence any side effects (i.e. anything other than fetching the next value) of the `next` method will occur.

        Returns:
            Peekable[S]: A new `Iterator` that allows peeking at the next element.

        Examples:
            Basic usage:
            ```python
            from pyochain import Range, Some

            xs = Range(1, 4)
            iterator = xs.iter().peekable()

            # peek() lets us see into the future
            assert iterator.peek() == Some(1)
            assert iterator.next() == Some(1)
            assert iterator.next() == Some(2)

            # we can peek() multiple times, the iterator won't advance
            assert iterator.peek() == Some(3)
            assert iterator.peek() == Some(3)
            assert iterator.next() == Some(3)

            # after the iterator is finished, so is peek()
            assert iterator.peek().is_none()
            assert iterator.next().is_none()
            ```
        """

    @overload
    def permutations(self, r: Literal[2]) -> PyoIterator[tuple[T, T]]: ...
    @overload
    def permutations(self, r: Literal[3]) -> PyoIterator[tuple[T, T, T]]: ...
    @overload
    def permutations(self, r: Literal[4]) -> PyoIterator[tuple[T, T, T, T]]: ...
    @overload
    def permutations(self, r: Literal[5]) -> PyoIterator[tuple[T, T, T, T, T]]: ...
    def permutations(self, r: int | None = None) -> PyoIterator[tuple[T, ...]]:
        """Return successive *r* length permutations of elements from the `Iterator`.

        The output is a subsequence of `product()` where entries with repeated elements have been filtered out.

        The length of the output is given by `math.perm()` which computes:

        `n! / (n - r)! when 0 ≤ r ≤ n or zero when r > n.`

        The permutation tuples are emitted in lexicographic order according to the order of the current `Iterator`, i.e `Self`.

        If `Self` is sorted, the output tuples will be produced in sorted order.

        Elements are treated as unique based on their position, not on their value.

        If `Self` elements are unique, there will be no repeated values within a permutation.

        Args:
            r (int | None): Length of each permutation. If not specified or `None`, defaults to the length of `Self`, and all possible full-length permutations are generated.

        Returns:
            PyoIterator[tuple[T, ...]]: An `Iterator` of permutations.

        Example:
            ```python
            from pyochain import Seq, Range

            a = Seq(1, 2, 3).iter().permutations(2).collect(Seq)
            assert a == ((1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2))

            b = Range(3).iter().permutations().collect(Seq)
            assert b == (
                (0, 1, 2),
                (0, 2, 1),
                (1, 0, 2),
                (1, 2, 0),
                (2, 0, 1),
                (2, 1, 0),
            )
            ```
        """

    @overload
    def product(self, /) -> PyoIterator[tuple[T]]: ...
    @overload
    def product[T2](self, iter2: Iterable[T2], /) -> PyoIterator[tuple[T, T2]]: ...
    @overload
    def product[T2, T3](
        self, iter2: Iterable[T2], iter3: Iterable[T3], /
    ) -> PyoIterator[tuple[T, T2, T3]]: ...
    @overload
    def product[T2, T3, T4](
        self, iter2: Iterable[T2], iter3: Iterable[T3], iter4: Iterable[T4], /
    ) -> PyoIterator[tuple[T, T2, T3, T4]]: ...
    @overload
    def product[T2, T3, T4, T5](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5]]: ...
    @overload
    def product[T2, T3, T4, T5, T6](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6]]: ...
    @overload
    def product[T2, T3, T4, T5, T6, T7](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        iter7: Iterable[T7],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7]]: ...
    @overload
    def product[T2, T3, T4, T5, T6, T7, T8](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        iter7: Iterable[T7],
        iter8: Iterable[T8],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7, T8]]: ...
    @overload
    def product[T2, T3, T4, T5, T6, T7, T8, T9](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        iter7: Iterable[T7],
        iter8: Iterable[T8],
        iter9: Iterable[T9],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7, T8, T9]]: ...
    @overload
    def product[T2, T3, T4, T5, T6, T7, T8, T9, T10](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        iter6: Iterable[T6],
        iter7: Iterable[T7],
        iter8: Iterable[T8],
        iter9: Iterable[T9],
        iter10: Iterable[T10],
        /,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7, T8, T9, T10]]: ...
    @overload
    def product[S](
        self: PyoIterator[S], *iterables: Iterable[S], repeat: int = ...
    ) -> PyoIterator[tuple[S, ...]]: ...
    def product(
        self, *iterables: Iterable[Any], repeat: int = 1
    ) -> PyoIterator[tuple[Any, ...]]:
        """Computes the Cartesian product with other `Iterable`.

        Roughly equivalent to nested for-loops as an `Iterator` method.

        ```python
        from pyochain import Iter

        assert Iter.once("A").iter().product("B").collect(tuple) == tuple(
            (x, y) for x in "A" for y in "B"
        )
        ```

        The nested loops cycle like an odometer with the rightmost element advancing on every iteration.

        This pattern creates a lexicographic ordering so that if the input iterables are sorted, the product tuples are emitted in sorted order.

        To compute the product of the current `Iterator` with itself, specify the number of repetitions with the optional repeat keyword argument.

        ```python
        from pyochain import Seq

        x = Seq(["A"])
        a = x.iter().product(repeat=4).collect(Seq)
        b = x.iter().product(x, x, x).collect(Seq)
        assert a == b
        ```
        Before `product()` runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products.

        Accordingly, it is only useful with finite inputs.

        Args:
            *iterables (Iterable[Any]): Other iterables to compute the Cartesian product with.
            repeat (int): The number of repetitions of the Cartesian product.

        Returns:
            PyoIterator[tuple[Any, ...]]: An iterable of tuples containing elements from the Cartesian product.

        Example:
            ```python
            from pyochain import Seq, Range, Iter

            colors = Seq("blue", "red")
            sizes = Seq("S", "M")
            a = colors.iter().product(sizes).collect(Seq)
            assert a == (("blue", "S"), ("blue", "M"), ("red", "S"), ("red", "M"))
            b = (
                colors
                .iter()
                .product(sizes)
                .map_star(lambda color, size: f"{color}-{size}")
                .collect(Seq)
            )
            assert b == ("blue-S", "blue-M", "red-S", "red-M")
            c = (
                Range(1, 4)
                .iter()
                .product((10, 20))
                .filter_star(lambda a, b: a * b >= 40)
                .collect(Seq)
            )
            assert c == ((2, 20), (3, 20))
            d = (
                Seq(26, 33)
                .iter()
                .product(("Michael", "Sophie"), ["Engineer"])
                .map_star(
                    lambda age, name, profession: f"{name} is {age} and is {profession}"
                )
                .collect(tuple)
            )
            assert d == (
                "Michael is 26 and is Engineer",
                "Sophie is 26 and is Engineer",
                "Michael is 33 and is Engineer",
                "Sophie is 33 and is Engineer",
            )
            e = Seq("blue", "red").iter().product(repeat=2).collect(Seq)
            assert e == (
                ("blue", "blue"),
                ("blue", "red"),
                ("red", "blue"),
                ("red", "red"),
            )
            ```
        """

    def reduce[S](self: PyoIterator[S], func: Callable[[S, S], S]) -> S:
        """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[[S, S], S]): Function to apply cumulatively to the items of the iterable.

        Returns:
            S: Single value resulting from cumulative reduction.

        Example:
            ```python
            from pyochain import Range

            assert Range(1, 4).iter().reduce(lambda a, b: a + b) == 6
            ```
        """

    def scan[U](self, initial: U, func: Callable[[U, T], Option[U]]) -> PyoIterator[U]:
        """Transform elements by sharing state between iterations.

        `scan` takes two arguments:

            - an **initial** value which seeds the internal state
            - a **func** with two arguments

        The first being a reference to the internal state and the second an iterator element.

        The **func** can assign to the internal state to share state between iterations.

        On iteration, the **func** will be applied to each element of the iterator and the return value from the func, an Option, is returned by the next method.

        Thus the **func** can return `Some(value)` to yield value, or `NONE` to end the iteration.

        Args:
            initial (U): Initial state.
            func (Callable[[U, T], Option[U]]): Function that takes the current state and an item, and returns an Option.

        Returns:
            PyoIterator[U]: An iterable of the yielded values.

        Example:
            ```python
            from pyochain import Some, NONE, Range, Seq, Option

            def accumulate_until_limit(state: int, item: int) -> Option[int]:
                new_state = state + item
                match new_state:
                    case _ if new_state <= 10:
                        return Some(new_state)
                    case _:
                        return NONE

            out = Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
            assert out == Seq(1, 3, 6, 10)
            ```
        """

    def skip(self, n: int) -> PyoIterator[T]:
        """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:
            PyoIterator[T]: An `Iterator` of the remaining elements.

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)

            assert data.iter().skip(1).collect(Seq) == Seq(2, 3)
            assert data.iter().skip(5).collect(Seq).is_empty()
            assert data.iter().skip(0).collect(Seq) == Seq(1, 2, 3)
            ```
        """

    def skip_while(self, predicate: Callable[[T], object]) -> PyoIterator[T]:
        """Skip elements from the `Iterator` while the *predicate* is `True`.

        Afterwards, returns every element.

        Note this does not produce any output until the predicate first becomes false, so this `Iterator` may have a lengthy start-up time.

        Note:
            This is strictly equivalent to `itertools::dropwhile(predicate, iterable)`.

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

        Returns:
            PyoIterator[T]: An `Iterator` of the items after skipping those for which the predicate is true.

        Example:
            ```python
            from pyochain import Seq

            out = Seq(1, 2, 0, -1).iter().skip_while(lambda x: x > 0).collect(Seq)
            assert out == Seq(0, -1)
            ```
        """

    def slice(
        self,
        start: int | None = None,
        stop: int | None = None,
        step: int | None = None,
    ) -> PyoIterator[T]:
        """Make an `Iterator` that returns selected elements from the iterable.

        Works like sequence slicing but does not support negative values for *start*, *stop*, or *step*.

        Elements are returned consecutively unless *step* is set higher than one which results in items being skipped.

        Args:
            start (int | None): Starting index. If zero or `None`, iteration starts at zero. Otherwise, elements from the `Iterator` are skipped until start is reached
            stop (int | None): Ending index. If `None`, iteration continues until the input is exhausted, if at all. Otherwise, it stops at the specified position.
            step (int | None): Step size for the slice. Defaults to one.

        Returns:
            PyoIterator[T]: An `Iterator` of the sliced items.

        Example:
            ```python
            from pyochain import Seq, Range

            txt = Seq("ABCDEFG")

            assert txt.iter().slice(stop=2).join("") == "AB"
            assert txt.iter().slice(2, 4).join("") == "CD"
            assert txt.iter().slice(2, None).join("") == "CDEFG"
            assert txt.iter().slice(0, None, 2).join("") == "ACEG"

            data = Range(1, 6)

            assert data.iter().slice(1, 4).collect(Seq) == (2, 3, 4)
            assert data.iter().slice(step=2).collect(Seq) == (1, 3, 5)
            assert data.iter().slice().collect(Seq) == (1, 2, 3, 4, 5)
            ```
        """

    def sort[U: SupportsRichComparison](
        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).

        This is strictly equivalent to `sorted(iterable, reverse=reverse)`.

        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 Vec

            assert Vec(3, 1, 2).iter().sort() == Vec(1, 2, 3)
            ```
        """

    def sort_by[S](
        self: PyoIterator[S],
        key: Callable[[S], SupportsRichComparison],
        *,
        reverse: bool = False,
    ) -> Vec[S]:
        """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[[S], SupportsRichComparison]): Function to extract a comparison key from each element.
            reverse (bool): Whether to sort in descending order.

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

        Example:
            ```python
            from pyochain import Seq, Vec

            str_numbers = Seq("3", "1", "2")
            assert str_numbers.iter().sort_by(int) == Vec("1", "2", "3")
            assert str_numbers.iter().sort_by(int, reverse=True) == Vec("3", "2", "1")
            from dataclasses import dataclass

            @dataclass
            class Person:
                name: str
                age: int

            peoples = Seq(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
            sorted_names = (
                peoples
                .iter()
                .sort_by(lambda x: x.age)
                .iter()
                .map(lambda x: x.name)
                .collect(Seq)
            )
            assert sorted_names == Seq("Bob", "Alice", "Charlie")
            ```
        """

    def step_by(self, step: int) -> PyoIterator[T]:
        """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:
            PyoIterator[T]: An `Iterator` of every nth item.

        Example:
            ```python
            from pyochain import Seq

            out = Seq(0, 1, 2, 3, 4, 5).iter().step_by(2).collect(Seq)
            assert out == Seq(0, 2, 4)
            ```
        """

    @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 Vec

            data = Vec(1, 2, 3)

            assert data.iter().sum() == 6
            data.clear()
            assert data.iter().sum() == 0
            assert data.iter().sum(10) == 10
            ```
        """

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

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

        Returns:
            PyoIterator[T]: An `Iterator` containing the last **n** elements.

        Example:
            ```python
            from pyochain import Range

            assert Range(10).iter().tail(2).collect(tuple) == (8, 9)
            ```
        """

    def take(self, n: int) -> PyoIterator[T]:
        """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:
            PyoIterator[T]: An `Iterator` of the first n items.

        Example:
            ```python
            from pyochain import Seq

            data = Seq(1, 2, 3)

            assert data.iter().take(2).collect(Seq) == Seq(1, 2)
            assert data.iter().take(5).collect(Seq) == Seq(1, 2, 3)
            ```
        """

    def take_while(self, predicate: Callable[[T], object]) -> PyoIterator[T]:
        """Yield elements from the `Iterator` as long as the predicate evaluates to `True`.

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

        Returns:
            PyoIterator[T]: An `Iterator` of the items taken while the predicate is true.

        Example:
            ```python
            from pyochain import Seq

            a = Seq(1, 2, 0).iter().take_while(lambda x: x > 0).collect(Seq)
            assert a == (1, 2)

            b = Seq(1, 4, 6, 3, 8).iter().take_while(lambda x: x < 5).collect(Seq)
            assert b == (1, 4)
            ```
        """

    def tee(self, n: int = 2) -> tuple[PyoIterator[T], ...]:
        """Split `Self` into `n` new independants `Iterators`.

        When the input iterable is already a tee iterator object, all members of the return tuple are constructed as if they had been produced by the upstream tee() call.

        This “flattening step” allows nested tee() calls to share the same underlying data chain and to have a single update step rather than a chain of calls.

        tee iterators are not threadsafe.

        A `RuntimeError` may be raised when simultaneously using iterators returned by the same `tee()` call, even if the original `Iterator` is threadsafe.

        This `Iterator` may require significant auxiliary storage (depending on how much temporary data needs to be stored).

        In general, if one `Iterator` uses most or all of the data before another `Iterator` starts, it is faster to use `collect()` instead of `tee()`.

        Args:
            n (int): The number of new `Iterators` to create. Defaults to 2.

        Returns:
            tuple[PyoIterator[T], ...]: A tuple of `n` new `Iterators` that can be used independently.

        Example:
            ```python
            from pyochain import Seq, Some

            data = Seq(1, 2, 3)
            it1, it2 = data.iter().tee()

            assert it1.collect(Seq) == data
            assert it2.collect(Seq) == data
            ```

            The flattening property makes tee iterators efficiently peekable:
            ```python
            from pyochain import Iter
            from pyochain.abc import PyoIterator

            def lookahead[T](tee_iterator: PyoIterator[T]) -> Option[T]:
                '''Return the next value without moving the input forward'''
                [forked_iterator] = tee_iterator.tee(1)
                return forked_iterator.next()

            iterator = Iter("abcdef")
            # Make the input peekable
            [iterator] = iterator.tee(1)
            # Move the iterator forward
            assert iterator.next() == Some("a")
            # Check next value
            assert lookahead(iterator) == Some("b")
            # Continue moving forward
            assert iterator.next() == Some("b")
            ```
        """

    @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]],
    ) -> 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 `Iterator` 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 Range, Some, Ok, Err, NONE, Vec, Option, Seq, Iter

            # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
            assert Range(1, 4).iter().map(Some).try_collect().unwrap() == Vec(1, 2, 3)
            # Failing to collect in the same way:
            assert Seq(Some(1), Some(2), NONE, Some(3)).iter().try_collect().is_none()

            # A similar example, but with Result:
            Range(1, 4).iter().map(Ok).try_collect().unwrap() == Vec(1, 2, 3)
            assert Seq(Ok(1), Err("error"), Ok(3)).iter().try_collect().is_none()

            def external_fn(x: int) -> Option[int]:
                if x % 2 == 0:
                    return Some(x)
                return NONE

            assert Range(1, 5).iter().map(external_fn).try_collect().is_none()
            # Demonstrating that the iterator remains usable after a failure:
            it = Iter(Some(1), NONE, Some(3), Some(4))
            assert it.try_collect().is_none()
            assert it.try_collect().unwrap() == Vec(3, 4)
            ```
        """

    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, Some

            def is_even(x: int) -> Result[bool, str]:
                return Ok(x % 2 == 0) if x >= 0 else Err("negative number")

            assert Range(1, 6).iter().try_find(is_even).unwrap().unwrap() == 2
            ```
        """

    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 Ok, Err, Result, Range, Iter, Seq

            def checked_add(acc: int, x: int) -> Result[int, str]:
                new_val = acc + x
                if new_val > 100:
                    return Err("overflow")
                else:
                    return Ok(new_val)

            assert Range(1, 4).iter().try_fold(0, checked_add).unwrap() == 6
            error = Iter.from_count(50, -10).take(5).try_fold(0, checked_add)
            assert error.unwrap_err() == "overflow"
            assert Seq().iter().try_fold(0, checked_add).unwrap() == 0
            ```
        """

    def try_for_each[E](self, f: Callable[[T], Result[Any, E]]) -> Result[tuple[()], E]:
        """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")

            assert Iter(1, 2, 3, 4, 5).try_for_each(validate_positive).is_ok()

            # Short-circuit on first error:
            error = Iter(1, 2, -1, 4).try_for_each(validate_positive).unwrap_err()
            assert error == "Value -1 is not positive"
            ```
        """

    def try_reduce[S, E](
        self: PyoIterator[S], func: Callable[[S, S], Result[S, E]]
    ) -> Result[Option[S], 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[[S, S], Result[S, E]]): Function that reduces two items, returns a `Result[S, E]`.

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

        Example:
            ```python
            from pyochain import Ok, Err, Result, Range, Seq

            def checked_add(x: int, y: int) -> Result[int, str]:
                if x + y > 100:
                    return Err("overflow")
                else:
                    return Ok(x + y)

            assert Range(1, 4).iter().try_reduce(checked_add).is_ok()
            assert Seq(50, 60).iter().try_reduce(checked_add).is_err()
            assert Range(0).iter().try_reduce(checked_add).unwrap().is_none()
            ```
        """

    def unique(self) -> PyoIterator[T]:
        """Return only unique elements of the `Iterator`.

        This has the same effect as collecting the `Iterator` into a `StableSet` (keeps original ordering), but this returns a new `Iterator`.

        This means that this operation stay lazy, and can be more efficient depending on the situation.

        If you just need unique elements in a collection right away, collecting the `Iterator` into a `set`-like collection may have more raw speed.

        Thus

        Returns:
            PyoIterator[T]: An `Iterator` of the unique items.

        Example:
            ```python
            from pyochain import Vec, Set, Seq

            data = Seq(1, 1, 2, 2, 3, 3)

            assert data.iter().unique().collect(Seq) == Seq(1, 2, 3)
            assert data.pipe(Set).iter().sort() == Vec(1, 2, 3)
            ```
        """

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

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

        Returns:
            PyoIterator[T]: An `Iterator` of the unique items.

        Example:
            ```python
            from pyochain import Seq

            data = Seq("cat", "mouse", "dog", "hen")
            assert data.iter().unique_by(key=len).collect(Seq) == Seq("cat", "mouse")
            ```
        """

    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 `Pipe::pipe`, but instead of passing `PyoIterator[T]`, we pass the elements inside `PyoIterator[T]`.

        This avoids you to do `iterator.pipe(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))

            assert 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.
            assert data.iter().unpack_into(lambda a, b, c: a + b + c) == 6
            ```
        """

    def unzip[U, V](
        self: PyoIterator[tuple[U, V]],
    ) -> tuple[PyoIterator[U], PyoIterator[V]]:
        """Converts an `Iterator` of pairs into a pair of `Iterator`s.

        This function is, in some sense, the opposite of [`zip`][].

        Both `Iterator`s share the same underlying source.

        Values consumed by one `Iterator` remain in the shared buffer until the other `Iterator` consumes them too.

        Returns:
            tuple[PyoIterator[U], PyoIterator[V]]: A tuple containing two `Iterator`s, one for each element of the pairs.

        Example:
            ```python
            from pyochain import Seq

            data = Seq("a", "b", "c")
            left, right = data.iter().enumerate().unzip()

            assert left.collect(Seq) == Seq(0, 1, 2)
            assert right.collect(Seq) == Seq("a", "b", "c")
            ```
        """

    def with_position(self) -> PyoIterator[tuple[Position, T]]:
        """Return an `Iterator` over (`Position`, `T`) tuples.

        The `Position` indicates whether the item `T` is the first, middle, last, or only element in the `Iterator`.

        Returns:
            PyoIterator[tuple[Position, T]]: An `Iterator` of (`Position`, item) tuples.

        Example:
            ```python
            from pyochain import Seq

            data = Seq("a", "b", "c", "d", "e")
            a = data.iter().with_position().collect(Seq)
            assert a == Seq(
                ("first", "a"),
                ("middle", "b"),
                ("middle", "c"),
                ("middle", "d"),
                ("last", "e"),
            )

            b = data.iter().take(1).with_position().collect(Seq)
            assert b == Seq([("only", "a")])

            c = data.iter().take(2).with_position().collect(Seq)
            assert c == Seq(("first", "a"), ("last", "b"))
            ```
        """

    @overload
    def zip(self, /, *, strict: bool = False) -> PyoIterator[tuple[T]]: ...
    @overload
    def zip[T2](
        self, iter2: Iterable[T2], /, *, strict: bool = False
    ) -> PyoIterator[tuple[T, T2]]: ...
    @overload
    def zip[T2, T3](
        self, iter2: Iterable[T2], iter3: Iterable[T3], /, *, strict: bool = False
    ) -> PyoIterator[tuple[T, T2, T3]]: ...
    @overload
    def zip[T2, T3, T4](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
        *,
        strict: bool = False,
    ) -> PyoIterator[tuple[T, T2, T3, T4]]: ...
    @overload
    def zip[T2, T3, T4, T5](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        /,
        *,
        strict: bool = False,
    ) -> PyoIterator[tuple[T, T2, T3, T4, T5]]: ...
    @overload
    def zip[S](
        self: PyoIterator[S], /, *others: Iterable[S], strict: bool = False
    ) -> PyoIterator[tuple[S, ...]]: ...
    def zip(
        self, /, *others: Iterable[Any], strict: bool = False
    ) -> PyoIterator[tuple[Any, ...]]:
        """Yields n-length tuples, where n is the number of iterables passed as positional arguments.

        The i-th element in every tuple comes from the i-th iterable argument to `.zip()`.

        This continues until the shortest argument is exhausted.

        Note:
            [`map_star`][] can then be used for subsequent operations on the index and value, in a destructuring manner.
            This keep the code clean and readable, without index access like `[0]` and `[1]` for inline lambdas.

        Args:
            *others (Iterable[Any]): Other iterables to zip with.
            strict (bool): If `True` and one of the arguments is exhausted before the others, raise a ValueError.

        Returns:
            PyoIterator[tuple[Any, ...]]: An `Iterator` of tuples containing elements from the zipped `PyoIterator` and other iterables.

        Example:
            ```python
            from pyochain import Seq

            a = Seq(1, 2).iter().zip((10, 20)).collect(Seq)
            assert a == Seq((1, 10), (2, 20))

            b = Seq("a", "b").iter().zip((1, 2, 3)).collect(Seq)
            assert b == Seq(("a", 1), ("b", 2))
            ```
        """

    @overload
    def zip_longest[T2](
        self, iter2: Iterable[T2], /
    ) -> PyoIterator[tuple[Option[T], Option[T2]]]: ...
    @overload
    def zip_longest[T2, T3](
        self, iter2: Iterable[T2], iter3: Iterable[T3], /
    ) -> PyoIterator[tuple[Option[T], Option[T2], Option[T3]]]: ...
    @overload
    def zip_longest[T2, T3, T4](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
    ) -> PyoIterator[tuple[Option[T], Option[T2], Option[T3], Option[T4]]]: ...
    @overload
    def zip_longest[T2, T3, T4, T5](
        self,
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        /,
    ) -> PyoIterator[
        tuple[Option[T], Option[T2], Option[T3], Option[T4], Option[T5]]
    ]: ...
    def zip_longest(self, *others: Iterable[Any]) -> ZippedLongest[T]:
        """Make an `Iterator` that aggregates elements from each of `Self` and input `Iterable`s.

        If the iterables are of uneven length, missing values are filled-in with `Null`.

        Otherwise, wrap elements in `Some` when they are present.

        Iteration continues until the longest iterable is exhausted.

        If one of the iterables is potentially infinite, then the resulting `Iterator` should be followed with a method that limits the number of calls.

        For example, [`slice`][] or [`take_while`][].

        Args:
            *others (Iterable[Any]): Other iterables to zip with.

        Returns:
            ZippedLongest[T]: An `Iterator` of tuples containing optional elements from the zipped iterables.

        Example:
            ```python
            from pyochain import Iter, Some, NONE, Vec, Seq

            out = Seq(1, 2).iter().zip_longest([10]).collect(Vec)
            assert out == [(Some(1), Some(10)), (Some(2), NONE)]

            # Can be combined with try collect to filter out the NONE:
            zipped = out.iter().map(lambda x: Iter(x).try_collect()).collect(Vec)
            assert zipped == [Some(Vec(1, 10)), NONE]
            ```
        """

from_count(start=0, step=1) classmethod

Create an Iterator of evenly spaced values, beginning with start.

Can be used with map() to generate consecutive data points or with zip() to add sequence numbers.

Warning

The Iterator returned is infinite, meaning it will never stop yielding elements.

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

Otherwise you could quickly run out of memory, if you try to collect it into a collection.

Parameters:

Name Type Description Default
start int

Starting value of the Iterator.

0
step int

Difference between consecutive values.

1

Returns:

Type Description
PyoIterator[int]

PyoIterator[int]: An Iterator of integers starting from start and increasing by step.

Example
from pyochain import Iter, Seq

assert Iter.from_count(10, 2).take(3).collect(Seq) == Seq(10, 12, 14)
assert Iter.from_count(-5, 5).take(4).collect(Seq) == Seq(-5, 0, 5, 10)
assert Iter.from_count(0, -1).take(5).collect(Seq) == (0, -1, -2, -3, -4)
x = Iter.from_count(0, 5).map(lambda x: x**2).take(4).collect(tuple)
assert x == (0, 25, 100, 225)
y = Iter.from_count(0, 5).zip([1, 2, 3]).collect(tuple)
assert y == ((0, 1), (5, 2), (10, 3))
Source code in pyochain/abc/_iterator.pyi
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
@classmethod
def from_count(cls, start: int = 0, step: int = 1) -> PyoIterator[int]:
    """Create an `Iterator` of evenly spaced values, beginning with *start*.

    Can be used with `map()` to generate consecutive data points or with `zip()` to add sequence numbers.

    Warning:
        The `Iterator` returned is **infinite**, meaning it will never stop yielding elements.

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

        Otherwise you could quickly run out of memory, if you try to collect it into a collection.

    Args:
        start (int): Starting value of the `Iterator`.
        step (int): Difference between consecutive values.

    Returns:
        PyoIterator[int]: An `Iterator` of integers starting from **start** and increasing by **step**.

    Example:
        ```python
        from pyochain import Iter, Seq

        assert Iter.from_count(10, 2).take(3).collect(Seq) == Seq(10, 12, 14)
        assert Iter.from_count(-5, 5).take(4).collect(Seq) == Seq(-5, 0, 5, 10)
        assert Iter.from_count(0, -1).take(5).collect(Seq) == (0, -1, -2, -3, -4)
        x = Iter.from_count(0, 5).map(lambda x: x**2).take(4).collect(tuple)
        assert x == (0, 25, 100, 225)
        y = Iter.from_count(0, 5).zip([1, 2, 3]).collect(tuple)
        assert y == ((0, 1), (5, 2), (10, 3))
        ```
    """

from_fn(f, *args, **kwargs) classmethod

Create an Iterator from a generator function.

The Callable must return:

  • Some(value) to yield a value
  • NONE to stop the iteration

You could consider this as a way to create an Iterator where the __next__() is the __call__() method.

As such, you can either provide lambdas, partials, closures, or pre-existing classes where __call__() is implemented, but a __next__() is not desired.

If you do have an Iterator class, simply pass it to the regular constructor, as this will be more efficient, ergonomic and idiomatic.

Parameters:

Name Type Description Default
f Callable[P, Option[R]]

Callable that returns the next item wrapped in Option.

required
*args P.args

Positional arguments to pass to f.

()
**kwargs P.kwargs

Keyword arguments to pass to f.

{}

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An Iterator yielding values produced by f.

Note

In Rust, this avoids defining a full struct and implementing Iterator for it when you have simple logic to generate values.

This is implemented for "Rust API compliance", but in Python, generators comprehensions/functions with yield statements are the ergonomic equivalent.

Example

Closure with captured local variable:

from pyochain import Iter, Some, NONE, Option

def make_counter(max_val: int):
    counter = 0

    def gen() -> Option[int]:
        nonlocal counter
        counter += 1
        return Some(counter) if counter <= max_val else NONE

    return gen

x = Iter.from_fn(make_counter(5)).collect(tuple)
assert x == (1, 2, 3, 4, 5)
Reading records from a text stream:
from io import StringIO

stream = StringIO("Alice\nBob\nCharlie\n")

def read_name() -> Option[str]:
    line = stream.readline()
    return Some(line.rstrip("\n")) if line else NONE

iterator = Iter.from_fn(read_name)
assert iterator.next() == Some("Alice")
assert iterator.next() == Some("Bob")
assert iterator.next() == Some("Charlie")
assert iterator.next().is_none()

Source code in pyochain/abc/_iterator.pyi
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
@classmethod
def from_fn[**P, R](
    cls, f: Callable[P, Option[R]], *args: P.args, **kwargs: P.kwargs
) -> PyoIterator[R]:
    r"""Create an `Iterator` from a generator function.

    The `Callable` must return:

    - `Some(value)` to yield a value
    - `NONE` to stop the iteration

    You could consider this as a way to create an `Iterator` where the `__next__()` is the `__call__()` method.

    As such, you can either provide lambdas, partials, closures, or pre-existing classes where `__call__()` is implemented, but a `__next__()` is not desired.

    If you do have an `Iterator` class, simply pass it to the regular constructor, as this will be more efficient, ergonomic and idiomatic.

    Args:
        f (Callable[P, Option[R]]): `Callable` that returns the next item wrapped in `Option`.
        *args (P.args): Positional arguments to pass to **f**.
        **kwargs (P.kwargs): Keyword arguments to pass to **f**.

    Returns:
        PyoIterator[R]: An `Iterator` yielding values produced by **f**.

    Note:
        In Rust, this avoids defining a full struct and implementing `Iterator` for it when you have simple logic to generate values.

        This is implemented for "Rust API compliance", but in Python, generators comprehensions/functions with `yield` statements are the ergonomic equivalent.

    Example:
        Closure with captured local variable:
        ```python
        from pyochain import Iter, Some, NONE, Option

        def make_counter(max_val: int):
            counter = 0

            def gen() -> Option[int]:
                nonlocal counter
                counter += 1
                return Some(counter) if counter <= max_val else NONE

            return gen

        x = Iter.from_fn(make_counter(5)).collect(tuple)
        assert x == (1, 2, 3, 4, 5)
        ```
        Reading records from a text stream:
        ```python
        from io import StringIO

        stream = StringIO("Alice\nBob\nCharlie\n")

        def read_name() -> Option[str]:
            line = stream.readline()
            return Some(line.rstrip("\n")) if line else NONE

        iterator = Iter.from_fn(read_name)
        assert iterator.next() == Some("Alice")
        assert iterator.next() == Some("Bob")
        assert iterator.next() == Some("Charlie")
        assert iterator.next().is_none()
        ```
    """

once(value) classmethod

Create an Iterator that yields a single value.

It's a bit more performant compared to Iter(value), since this bypass the runtime checks in its constructor.

Parameters:

Name Type Description Default
value V

The single value to yield.

required

Returns:

Type Description
PyoIterator[V]

PyoIterator[V]: An Iterator yielding the specified value.

Example
from pyochain import Iter, Seq

assert Iter.once(42).collect(Seq) == Seq(
    42,
)
Source code in pyochain/abc/_iterator.pyi
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
@classmethod
def once[V](cls, value: V) -> PyoIterator[V]:
    """Create an `Iterator` that yields a single value.

    It's a bit more performant compared to `Iter(value)`, since this bypass the runtime checks in its constructor.

    Args:
        value (V): The single value to yield.

    Returns:
        PyoIterator[V]: An `Iterator` yielding the specified value.

    Example:
        ```python
        from pyochain import Iter, Seq

        assert Iter.once(42).collect(Seq) == Seq(
            42,
        )
        ```
    """

once_with(func, *args, **kwargs) classmethod

Create an Iterator that lazily generates a value exactly once by invoking the provided closure.

If you have a function which works on iterators, but you only need to process one value, you can use this method rather than doing something like Iter([value]).

This can be considered the lazy counterpart of once.

Parameters:

Name Type Description Default
func Callable[P, R]

The single value to yield.

required
*args P.args

Positional arguments to pass to func.

()
**kwargs P.kwargs

Keyword arguments to pass to func.

{}

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An Iterator yielding the specified value.

Example
from pyochain import Iter, Seq

assert Iter.once_with(lambda: 42).collect(Seq) == Seq(
    42,
)
Source code in pyochain/abc/_iterator.pyi
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
@classmethod
def once_with[**P, R](
    cls, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
) -> PyoIterator[R]:
    """Create an `Iterator`  that lazily generates a value exactly once by invoking the provided closure.

    If you have a function which works on iterators, but you only need to process one value, you can use this method rather than doing something like `Iter([value])`.

    This can be considered the lazy counterpart of [`once`][].

    Args:
        func (Callable[P, R]): The single value to yield.
        *args (P.args): Positional arguments to pass to **func**.
        **kwargs (P.kwargs): Keyword arguments to pass to **func**.

    Returns:
        PyoIterator[R]: An `Iterator` yielding the specified value.

    Example:
        ```python
        from pyochain import Iter, Seq

        assert Iter.once_with(lambda: 42).collect(Seq) == Seq(
            42,
        )
        ```
    """

repeat(obj, n=None) classmethod

Repeat the provided object n times as elements of an Iterator.

If n is None, this will create an infinite Iterator.

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

Warning

Each repetition is a reference to the same object, not a copy.

This means that if the object is mutable and you modify one of the repetitions, all next repetitions will reflect that change.

Parameters:

Name Type Description Default
obj O

The object to repeat.

required
n int | None

Optional number of repetitions.

None

Returns:

Type Description
PyoIterator[O]

PyoIterator[O]: An Iterator of repeated obj.

See Also

cycle to repeat the elements of the Iterator.

Example

from pyochain import Seq, Iter

assert Iter.repeat(1, 3).collect(Seq) == (1, 1, 1)
assert Iter.repeat(("a", "b"), 2).collect(Seq) == (("a", "b"), ("a", "b"))
A common use for repeat is to supply a stream of constant values to map or zip:
from pyochain import Range

out = Range(10).iter().map_with(pow, Iter.repeat(2)).collect(Seq)
assert out == (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

Shared reference behavior:

from pyochain import Vec

base = ["Alice", "Bob", "Charlie"]

first, second = Iter.repeat(base).take(2).collect(tuple)
first.append("Joe")

assert first == ["Alice", "Bob", "Charlie", "Joe"]
assert base == ["Alice", "Bob", "Charlie", "Joe"]
assert second == ["Alice", "Bob", "Charlie", "Joe"]
assert first is second and first is base and second is base

Source code in pyochain/abc/_iterator.pyi
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
@classmethod
def repeat[O](cls, obj: O, n: int | None = None) -> PyoIterator[O]:
    """Repeat the provided object **n** times as elements of an `Iterator`.

    If **n** is `None`, this will create an infinite `Iterator`.

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

    Warning:
        Each repetition is a reference to the same object, not a copy.

        This means that if the object is mutable and you modify one of the repetitions, all next repetitions will reflect that change.

    Args:
        obj (O): The object to repeat.
        n (int | None): Optional number of repetitions.

    Returns:
        PyoIterator[O]: An `Iterator` of repeated **obj**.

    See Also:
        [`cycle`][] to repeat the **elements** of the `Iterator`.

    Example:
        ```python
        from pyochain import Seq, Iter

        assert Iter.repeat(1, 3).collect(Seq) == (1, 1, 1)
        assert Iter.repeat(("a", "b"), 2).collect(Seq) == (("a", "b"), ("a", "b"))
        ```
        A common use for repeat is to supply a stream of constant values to map or zip:
        ```python
        from pyochain import Range

        out = Range(10).iter().map_with(pow, Iter.repeat(2)).collect(Seq)
        assert out == (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
        ```

        Shared reference behavior:
        ```python
        from pyochain import Vec

        base = ["Alice", "Bob", "Charlie"]

        first, second = Iter.repeat(base).take(2).collect(tuple)
        first.append("Joe")

        assert first == ["Alice", "Bob", "Charlie", "Joe"]
        assert base == ["Alice", "Bob", "Charlie", "Joe"]
        assert second == ["Alice", "Bob", "Charlie", "Joe"]
        assert first is second and first is base and second is base
        ```
    """

successors(first, succ) classmethod

Create an iterator of successive values computed from the previous one.

The iterator yields first (if it is Some), then repeatedly applies succ to the previous yielded value until it returns NONE.

Parameters:

Name Type Description Default
first Option[U]

Initial item.

required
succ Callable[[U], Option[U]]

Successor function.

required

Returns:

Type Description
PyoIterator[U]

PyoIterator[U]: Iterator yielding first and its successors.

Example
from pyochain import Iter, Some, NONE, Option, Seq

def next_pow10(x: int) -> Option[int]:
    return Some(x * 10) if x < 10_000 else NONE

a = Iter.successors(Some(1), next_pow10).collect(Seq)
assert a == (1, 10, 100, 1000, 10000)
b = Iter.successors(NONE, next_pow10).collect(Seq)
assert b == ()
Source code in pyochain/abc/_iterator.pyi
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
@classmethod
def successors[U](
    cls, first: Option[U], succ: Callable[[U], Option[U]]
) -> PyoIterator[U]:
    """Create an iterator of successive values computed from the previous one.

    The iterator yields `first` (if it is `Some`), then repeatedly applies **succ** to the
    previous yielded value until it returns `NONE`.

    Args:
        first (Option[U]): Initial item.
        succ (Callable[[U], Option[U]]): Successor function.

    Returns:
        PyoIterator[U]: `Iterator` yielding `first` and its successors.

    Example:
        ```python
        from pyochain import Iter, Some, NONE, Option, Seq

        def next_pow10(x: int) -> Option[int]:
            return Some(x * 10) if x < 10_000 else NONE

        a = Iter.successors(Some(1), next_pow10).collect(Seq)
        assert a == (1, 10, 100, 1000, 10000)
        b = Iter.successors(NONE, next_pow10).collect(Seq)
        assert b == ()
        ```
    """

accumulate(func=None, initial=None)

accumulate(
    func: None = None, initial: S | None = None
) -> PyoIterator[S]
accumulate(
    func: Callable[[I, N], I], initial: I | None = None
) -> PyoIterator[I]

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.

function should accept two arguments, an accumulated total and a value from the Iterator.

Parameters:

Name Type Description Default
func Callable[[S, S], S] | None

Optional binary function to apply cumulatively. If None, the default is to use addition (operator.add).

None
initial S | None

Optional initial value to start the accumulation.

None

Returns:

Type Description
PyoIterator[S]

PyoIterator[S]: A new Iterator with accumulated results.

Example

import operator as op
from pyochain import Seq

s = Seq(1, 2, 3)
assert s.iter().accumulate().collect(tuple) == (1, 3, 6)
assert s.iter().accumulate(initial=10).collect(tuple) == (10, 11, 13, 16)
assert s.iter().accumulate(op.mul).collect(tuple) == (1, 2, 6)
assert s.iter().accumulate(op.add, 0).collect(Seq) == (0, 1, 3, 6)
# The final accumulated result is the same as fold:
assert s.iter().fold(0, op.add) == 6
assert s.iter().accumulate(op.mul).collect(Seq) == (1, 2, 6)
assert s.iter().accumulate().collect(Seq) == (1, 3, 6)
To compute a running minimum, set function to min().

For a running maximum, set function to max().

Or for a running product, set function to operator.mul().

To build an amortization table, accumulate the interest and apply payments:

from pyochain import Iter
import operator

data = Seq(3, 4, 6, 2, 1, 9, 0, 7, 5, 8)
running_max = data.iter().accumulate(max).collect(Seq)
assert running_max == (3, 4, 6, 6, 6, 9, 9, 9, 9, 9)

running_product = data.iter().accumulate(operator.mul).collect(Seq)
assert running_product == (3, 12, 72, 144, 144, 1296, 0, 0, 0, 0)

# Amortize a 5% loan of 1000 with 10 annual payments of 90
update = lambda balance, payment: round(balance * 1.05) - payment
res = Iter.repeat(90, 10).accumulate(update, initial=1_000).collect(list)
assert res == [1000, 960, 918, 874, 828, 779, 728, 674, 618, 559, 497]

Source code in pyochain/abc/_iterator.pyi
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
def accumulate[S](
    self: PyoIterator[S],
    func: Callable[[S, S], S] | None = None,
    initial: S | None = None,
) -> PyoIterator[S]:
    """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.

    **function** should accept two arguments, an accumulated total and a value from the `Iterator`.

    Args:
        func (Callable[[S, S], S] | None): Optional binary function to apply cumulatively. If `None`, the default is to use addition (`operator.add`).
        initial (S | None): Optional initial value to start the accumulation.

    Returns:
        PyoIterator[S]: A new `Iterator` with accumulated results.

    Example:
        ```python
        import operator as op
        from pyochain import Seq

        s = Seq(1, 2, 3)
        assert s.iter().accumulate().collect(tuple) == (1, 3, 6)
        assert s.iter().accumulate(initial=10).collect(tuple) == (10, 11, 13, 16)
        assert s.iter().accumulate(op.mul).collect(tuple) == (1, 2, 6)
        assert s.iter().accumulate(op.add, 0).collect(Seq) == (0, 1, 3, 6)
        # The final accumulated result is the same as fold:
        assert s.iter().fold(0, op.add) == 6
        assert s.iter().accumulate(op.mul).collect(Seq) == (1, 2, 6)
        assert s.iter().accumulate().collect(Seq) == (1, 3, 6)
        ```
        To compute a running minimum, set function to `min()`.

        For a running maximum, set function to `max()`.

        Or for a running product, set function to `operator.mul()`.

        To build an amortization table, accumulate the interest and apply payments:
        ```python
        from pyochain import Iter
        import operator

        data = Seq(3, 4, 6, 2, 1, 9, 0, 7, 5, 8)
        running_max = data.iter().accumulate(max).collect(Seq)
        assert running_max == (3, 4, 6, 6, 6, 9, 9, 9, 9, 9)

        running_product = data.iter().accumulate(operator.mul).collect(Seq)
        assert running_product == (3, 12, 72, 144, 144, 1296, 0, 0, 0, 0)

        # Amortize a 5% loan of 1000 with 10 annual payments of 90
        update = lambda balance, payment: round(balance * 1.05) - payment
        res = Iter.repeat(90, 10).accumulate(update, initial=1_000).collect(list)
        assert res == [1000, 960, 918, 874, 828, 779, 728, 674, 618, 559, 497]
        ```
    """

all(predicate=None)

Tests if every element of the Iterator is truthy.

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 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 Seq

assert Seq(1, True).iter().all()
assert Seq().iter().all()
assert not Seq(1, 0).iter().all()

def is_even(x: int) -> bool:
    return x % 2 == 0

assert Seq(2, 4, 6).iter().all(is_even)
assert not Seq("a", "", "c").iter().all()
assert not Seq(1, None, 3).iter().all()
Source code in pyochain/abc/_iterator.pyi
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
def all(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if every element of the `Iterator` is truthy.

    `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 `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 Seq

        assert Seq(1, True).iter().all()
        assert Seq().iter().all()
        assert not Seq(1, 0).iter().all()

        def is_even(x: int) -> bool:
            return x % 2 == 0

        assert Seq(2, 4, 6).iter().all(is_even)
        assert not Seq("a", "", "c").iter().all()
        assert not Seq(1, None, 3).iter().all()
        ```
    """

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 Seq, Range

assert Seq("AaaA").iter().all_equal(key=str.casefold)
assert Range(9).iter().all_equal(key=lambda x: x < 10)
assert not Range(9).iter().all_equal()
Source code in pyochain/abc/_iterator.pyi
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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 Seq, Range

        assert Seq("AaaA").iter().all_equal(key=str.casefold)
        assert Range(9).iter().all_equal(key=lambda x: x < 10)
        assert not Range(9).iter().all_equal()
        ```
    """

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 Seq, Set

assert not Seq("ABCB").iter().all_unique()
assert Seq("ABCb").iter().all_unique()

# Alternative way to check uniqueness by comparing lengths:
collection = Seq(1, 2, 3, 3)
assert not collection.len() == collection.pipe(Set).len()
Source code in pyochain/abc/_iterator.pyi
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
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 Seq, Set

        assert not Seq("ABCB").iter().all_unique()
        assert Seq("ABCb").iter().all_unique()

        # Alternative way to check uniqueness by comparing lengths:
        collection = Seq(1, 2, 3, 3)
        assert not collection.len() == collection.pipe(Set).len()
        ```
    """

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 Seq

assert Seq("ABCb").iter().all_unique()
assert not Seq("ABCb").iter().all_unique_by(str.lower)
Source code in pyochain/abc/_iterator.pyi
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
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 Seq

        assert Seq("ABCb").iter().all_unique()
        assert not Seq("ABCb").iter().all_unique_by(str.lower)
        ```
    """

any(predicate=None)

Tests if any element of the Iterator is truthy.

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 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 Seq, Range

assert Seq(0, 1).iter().any()
assert not Range(0).iter().any()

def is_even(x: int) -> bool:
    return x % 2 == 0

assert Seq(1, 3, 4).iter().any(is_even)
Source code in pyochain/abc/_iterator.pyi
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
def any(self, predicate: Callable[[T], bool] | None = None) -> bool:
    """Tests if any element of the `Iterator` is truthy.

    `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 `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 Seq, Range

        assert Seq(0, 1).iter().any()
        assert not Range(0).iter().any()

        def is_even(x: int) -> bool:
            return x % 2 == 0

        assert Seq(1, 3, 4).iter().any(is_even)
        ```
    """

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

assert Iter("abcdefghabcd").arg_max() == 7
assert 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
assert models.get(accuracy.iter().arg_max()).unwrap() == "knn"

# Best accuracy
assert accuracy.iter().max() == 84

Source code in pyochain/abc/_iterator.pyi
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
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

        assert Iter("abcdefghabcd").arg_max() == 7
        assert 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
        assert models.get(accuracy.iter().arg_max()).unwrap() == "knn"

        # Best accuracy
        assert accuracy.iter().max() == 84
        ```
    """

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 Seq

assert Seq("a", "bbb", "cc").iter().arg_max_by(len) == 1
assert Seq("Alice", "bob", "charlie").iter().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
assert models.get(accuracy.iter().arg_max_by(int)).unwrap() == "knn"

# Best accuracy
assert accuracy.iter().max_by(int) == "84"

Source code in pyochain/abc/_iterator.pyi
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
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 Seq

        assert Seq("a", "bbb", "cc").iter().arg_max_by(len) == 1
        assert Seq("Alice", "bob", "charlie").iter().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
        assert models.get(accuracy.iter().arg_max_by(int)).unwrap() == "knn"

        # Best accuracy
        assert accuracy.iter().max_by(int) == "84"
        ```
    """

arg_min()

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

Credits to more-itertools for the examples.

Returns:

Name Type Description
int int

The index of the minimum value.

Example
from pyochain import Seq

assert Seq("efghabcdijkl").iter().arg_min() == 4
assert Seq(3, 2, 1, 0, 4, 2, 1, 0).iter().arg_min() == 3
Source code in pyochain/abc/_iterator.pyi
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def arg_min(self) -> int:
    """Index of the first occurrence of a minimum value in the `Iterator`.

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

    Returns:
        int: The index of the minimum value.

    Example:
        ```python
        from pyochain import Seq

        assert Seq("efghabcdijkl").iter().arg_min() == 4
        assert Seq(3, 2, 1, 0, 4, 2, 1, 0).iter().arg_min() == 3
        ```
    """

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 Seq

assert Seq("aaa", "b", "cc").iter().arg_min_by(len) == 1
assert Seq("Alice", "bob", "Charlie").iter().arg_min_by(str.lower) == 0
Find the fastest healing family member based on age:
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
assert labels.get(ages.iter().arg_min_by(cost)).unwrap() == "bart"
# Age with fastest healing
assert ages.iter().min_by(key=cost) == 10

Source code in pyochain/abc/_iterator.pyi
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
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 Seq

        assert Seq("aaa", "b", "cc").iter().arg_min_by(len) == 1
        assert Seq("Alice", "bob", "Charlie").iter().arg_min_by(str.lower) == 0
        ```
        Find the fastest healing family member based on age:
        ```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
        assert labels.get(ages.iter().arg_min_by(cost)).unwrap() == "bart"
        # Age with fastest healing
        assert ages.iter().min_by(key=cost) == 10
        ```
    """

batched(n, *, strict=False)

batched(
    n: Literal[1], *, strict: Literal[True]
) -> PyoIterator[tuple[T]]
batched(
    n: Literal[2], *, strict: Literal[True]
) -> PyoIterator[tuple[T, T]]
batched(
    n: Literal[3], *, strict: Literal[True]
) -> PyoIterator[tuple[T, T, T]]
batched(
    n: Literal[4], *, strict: Literal[True]
) -> PyoIterator[tuple[T, T, T, T]]
batched(
    n: Literal[5], *, strict: Literal[True]
) -> PyoIterator[tuple[T, T, T, T, T]]
batched(
    n: int, *, strict: Literal[False]
) -> PyoIterator[tuple[T, ...]]
batched(
    n: int, *, strict: bool = False
) -> PyoIterator[tuple[T, ...]]

Batch elements into tuples of length n and return a new Iterator.

  • The last batch may be shorter than n.
  • The data is consumed lazily, just enough to fill a batch.
  • The result is yielded as soon as a batch is full or when the Iterator is exhausted.
Note

This is the closest equivalent to Iterator::array_chunks in Rust.

Parameters:

Name Type Description Default
n int

Number of elements in each batch.

required
strict bool

If True, raises a ValueError if the last batch is not of length n.

False

Returns:

Type Description
PyoIterator[tuple[T, ...]]

PyoIterator[tuple[T, ...]]: An iterable of batched tuples.

Example

from pyochain import Seq

a = Seq("ABCDEFG").iter().batched(3).collect(Seq)
b = (("A", "B", "C"), ("D", "E", "F"), ("G",))
assert a == b
data = Seq(1, 1, 2, -2, 6, 0, 3, 1, 0)
#           ^-----^  ^------^  ^-----^
assert data.iter().batched(3, strict=True).map(sum).all(lambda x: x == 4)
You can use it to group elements into fixed-size groups.
from pyochain import Vec

flattened_data = Vec("roses", "red", "violets", "blue", "sugar", "sweet")
unflattened = flattened_data.iter().batched(2).collect(Vec)
assert unflattened == [
    ("roses", "red"),
    ("violets", "blue"),
    ("sugar", "sweet"),
]

Source code in pyochain/abc/_iterator.pyi
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
def batched(self, n: int, *, strict: bool = False) -> PyoIterator[tuple[T, ...]]:
    """Batch elements into tuples of length n and return a new `Iterator`.

    - The last batch may be shorter than n.
    - The data is consumed lazily, just enough to fill a batch.
    - The result is yielded as soon as a batch is full or when the `Iterator` is exhausted.

    Note:
        This is the closest equivalent to `Iterator::array_chunks` in Rust.

    Args:
        n (int): Number of elements in each batch.
        strict (bool): If `True`, raises a ValueError if the last batch is not of length n.

    Returns:
        PyoIterator[tuple[T, ...]]: An iterable of batched tuples.

    Example:
        ```python
        from pyochain import Seq

        a = Seq("ABCDEFG").iter().batched(3).collect(Seq)
        b = (("A", "B", "C"), ("D", "E", "F"), ("G",))
        assert a == b
        data = Seq(1, 1, 2, -2, 6, 0, 3, 1, 0)
        #           ^-----^  ^------^  ^-----^
        assert data.iter().batched(3, strict=True).map(sum).all(lambda x: x == 4)
        ```
        You can use it to group elements into fixed-size groups.
        ```python
        from pyochain import Vec

        flattened_data = Vec("roses", "red", "violets", "blue", "sugar", "sweet")
        unflattened = flattened_data.iter().batched(2).collect(Vec)
        assert unflattened == [
            ("roses", "red"),
            ("violets", "blue"),
            ("sugar", "sweet"),
        ]
        ```
    """

chain(*others)

chain(o1: Iterable[O1]) -> PyoIterator[S | O1]
chain(
    o1: Iterable[O1], o2: Iterable[O2]
) -> PyoIterator[S | O1 | O2]
chain(
    o1: Iterable[O1], o2: Iterable[O2], o3: Iterable[O3]
) -> PyoIterator[S | O1 | O2 | O3]
chain(
    o1: Iterable[O1],
    o2: Iterable[O2],
    o3: Iterable[O3],
    o4: Iterable[O4],
) -> PyoIterator[S | O1 | O2 | O3 | O4]
chain(
    o1: Iterable[O1],
    o2: Iterable[O2],
    o3: Iterable[O3],
    o4: Iterable[O4],
    o5: Iterable[O5],
) -> PyoIterator[S | O1 | O2 | O3 | O4 | O5]

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.

Tip

You can use Iter.once() with chain() for lazily prepending values to an already existing Iterator.

Parameters:

Name Type Description Default
*others Iterable[O]

Other iterables to concatenate.

()

Returns:

Type Description
PyoIterator[S | O]

PyoIterator[S | O]: 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 Seq, Iter, Range

data = Seq(1, 2)
# Multiple iterables of different types can be chained together:
mixed = data.iter().chain((3, 4), [True], "hi").collect(Seq)
assert mixed == (1, 2, 3, 4, True, "h", "i")
# You can also chain infinite iterators,
chained = (
    data
    .iter()
    .chain(Iter.from_count(3))
    .chain(Iter.from_count(2).map(lambda _: "unreachable"))
    .take(5)
    .collect(Seq)
)
assert chained == (1, 2, 3, 4, 5)
Source code in pyochain/abc/_iterator.pyi
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
def chain[S, O](self: PyoIterator[S], *others: Iterable[O]) -> PyoIterator[S | O]:
    """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`.

    Tip:
        You can use `Iter.once()` with `chain()` for lazily prepending values to an already existing `Iterator`.

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

    Returns:
        PyoIterator[S | O]: 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 Seq, Iter, Range

        data = Seq(1, 2)
        # Multiple iterables of different types can be chained together:
        mixed = data.iter().chain((3, 4), [True], "hi").collect(Seq)
        assert mixed == (1, 2, 3, 4, True, "h", "i")
        # You can also chain infinite iterators,
        chained = (
            data
            .iter()
            .chain(Iter.from_count(3))
            .chain(Iter.from_count(2).map(lambda _: "unreachable"))
            .take(5)
            .collect(Seq)
        )
        assert chained == (1, 2, 3, 4, 5)
        ```
    """

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 Pipe::pipe 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 Pipe::pipe instead.

Parameters:

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

Function|type that defines the target 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(4)
assert data.iter().collect(list) == [0, 1, 2, 3]
assert data.iter().collect(Vec) == Vec(0, 1, 2, 3)
assert data.iter().map(str).enumerate().collect(dict) == {
    0: "0",
    1: "1",
    2: "2",
    3: "3",
}
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(5)
    .iter()
    .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
    .collect(Seq[Result[int, int]])
)
assert data.pipe(repr) == "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 pyochain/abc/_iterator.pyi
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
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 `Pipe::pipe` 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 [`Pipe::pipe`][Pipe.pipe] instead.

    Args:
        collector (Callable[[Iterator[T]], R]): Function|type that defines the target collection.

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

    Example:
        ```python
        from pyochain import Iter, Range, Vec, Dict

        data = Range(4)
        assert data.iter().collect(list) == [0, 1, 2, 3]
        assert data.iter().collect(Vec) == Vec(0, 1, 2, 3)
        assert data.iter().map(str).enumerate().collect(dict) == {
            0: "0",
            1: "1",
            2: "2",
            3: "3",
        }
        ```
        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(5)
            .iter()
            .map(lambda x: Ok(x) if x % 2 == 0 else Err(x))
            .collect(Seq[Result[int, int]])
        )
        assert data.pipe(repr) == "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.
    """

collect_into(collection)

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

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(2, 3)
vec = Vec(1)
b = a.iter().map(lambda x: x * 2).collect_into(vec)
assert b == Vec(1, 4, 6)
c = a.iter().map(lambda x: x * 10).collect_into(vec)
assert c == Vec(1, 4, 6, 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()
assert a.iter().collect_into(vec).len() == vec.len()
assert a.iter().collect_into(vec).len() == vec.len()

Source code in pyochain/abc/_iterator.pyi
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
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(2, 3)
        vec = Vec(1)
        b = a.iter().map(lambda x: x * 2).collect_into(vec)
        assert b == Vec(1, 4, 6)
        c = a.iter().map(lambda x: x * 10).collect_into(vec)
        assert c == Vec(1, 4, 6, 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()
        assert a.iter().collect_into(vec).len() == vec.len()
        assert a.iter().collect_into(vec).len() == vec.len()
        ```
    """

combinations(r)

combinations(r: Literal[2]) -> PyoIterator[tuple[T, T]]
combinations(r: Literal[3]) -> PyoIterator[tuple[T, T, T]]
combinations(
    r: Literal[4],
) -> PyoIterator[tuple[T, T, T, T]]
combinations(
    r: Literal[5],
) -> PyoIterator[tuple[T, T, T, T, T]]

Return an Iterator of tuple with r elements of type T.

The output is a subsequence of product(), keeping only entries that are subsequences of the Iterator.

The length of the output is given by math.comb() which computes the following:

n! / r! / (n - r)! when 0 ≤ r ≤ n or zero when r > n.

The combination tuples are emitted in lexicographic order according to the order of the Iterator.

If the latter is sorted, the output tuples will be produced in sorted order.

Parameters:

Name Type Description Default
r int

Length of each combination.

required

Returns:

Type Description
PyoIterator[tuple[T, ...]]

PyoIterator[tuple[T, ...]]: An Iterator of combinations.

Example
from pyochain import Seq, Iter, Range

a = Iter("ABCD").combinations(2).collect(Seq)
assert a == (
    ("A", "B"),
    ("A", "C"),
    ("A", "D"),
    ("B", "C"),
    ("B", "D"),
    ("C", "D"),
)
b = Range(4).iter().combinations(3).collect(Seq)
assert b == (
    (0, 1, 2),
    (0, 1, 3),
    (0, 2, 3),
    (1, 2, 3),
)

combined = Seq(1, 2, 3).iter().combinations(2).collect(Seq)
assert combined == ((1, 2), (1, 3), (2, 3))
Source code in pyochain/abc/_iterator.pyi
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
def combinations(self, r: int) -> PyoIterator[tuple[T, ...]]:
    """Return an `Iterator` of `tuple` with **r** elements of type `T`.

    The output is a subsequence of `product()`, keeping only entries that are subsequences of the `Iterator`.

    The length of the output is given by `math.comb()` which computes the following:

    `n! / r! / (n - r)!` when `0 ≤ r ≤ n` or zero when `r > n`.

    The combination `tuples` are emitted in lexicographic order according to the order of the `Iterator`.

    If the latter is sorted, the output tuples will be produced in sorted order.

    Args:
        r (int): Length of each combination.

    Returns:
        PyoIterator[tuple[T, ...]]: An `Iterator` of combinations.

    Example:
        ```python
        from pyochain import Seq, Iter, Range

        a = Iter("ABCD").combinations(2).collect(Seq)
        assert a == (
            ("A", "B"),
            ("A", "C"),
            ("A", "D"),
            ("B", "C"),
            ("B", "D"),
            ("C", "D"),
        )
        b = Range(4).iter().combinations(3).collect(Seq)
        assert b == (
            (0, 1, 2),
            (0, 1, 3),
            (0, 2, 3),
            (1, 2, 3),
        )

        combined = Seq(1, 2, 3).iter().combinations(2).collect(Seq)
        assert combined == ((1, 2), (1, 3), (2, 3))
        ```
    """

combinations_with_replacement(r)

combinations_with_replacement(
    r: Literal[2],
) -> PyoIterator[tuple[T, T]]
combinations_with_replacement(
    r: Literal[3],
) -> PyoIterator[tuple[T, T, T]]
combinations_with_replacement(
    r: Literal[4],
) -> PyoIterator[tuple[T, T, T, T]]
combinations_with_replacement(
    r: Literal[5],
) -> PyoIterator[tuple[T, T, T, T, T]]

Return r length subsequences of elements from the Iterator, allowing individual elements to be repeated more than once.

The output is a subsequence of product() that keeps only entries that are subsequences (with possible repeated elements) of the iterable.

The number of subsequence returned is:

(n + r - 1)! / r! / (n - 1)! when n > 0.

The combination tuples are emitted in lexicographic order according to the order of the Iterator.

If the Iterator is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value.

If the input elements are unique, the generated combinations will also be unique.

Parameters:

Name Type Description Default
r int

Length of each combination.

required

Returns:

Type Description
PyoIterator[tuple[T, ...]]

PyoIterator[tuple[T, ...]]: An Iterator of combinations with replacement.

Example
from pyochain import Range, Seq, Iter

a = Seq(1, 2, 3).iter().combinations_with_replacement(2).collect(Seq)
assert a == ((1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3))
b = Iter("ABC").combinations_with_replacement(2).collect(Seq)
assert b == (
    ("A", "A"),
    ("A", "B"),
    ("A", "C"),
    ("B", "B"),
    ("B", "C"),
    ("C", "C"),
)
Source code in pyochain/abc/_iterator.pyi
 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
def combinations_with_replacement(self, r: int) -> PyoIterator[tuple[T, ...]]:
    """Return r length subsequences of elements from the `Iterator`, allowing individual elements to be repeated more than once.

    The output is a subsequence of `product()` that keeps only entries that are subsequences (with possible repeated elements) of the iterable.

    The number of subsequence returned is:

    `(n + r - 1)! / r! / (n - 1)!` when `n > 0`.

    The combination tuples are emitted in lexicographic order according to the order of the `Iterator`.

    If the `Iterator` is sorted, the output tuples will be produced in sorted order.

    Elements are treated as unique based on their position, not on their value.

    If the input elements are unique, the generated combinations will also be unique.

    Args:
        r (int): Length of each combination.

    Returns:
        PyoIterator[tuple[T, ...]]: An `Iterator` of combinations with replacement.

    Example:
        ```python
        from pyochain import Range, Seq, Iter

        a = Seq(1, 2, 3).iter().combinations_with_replacement(2).collect(Seq)
        assert a == ((1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3))
        b = Iter("ABC").combinations_with_replacement(2).collect(Seq)
        assert b == (
            ("A", "A"),
            ("A", "B"),
            ("A", "C"),
            ("B", "B"),
            ("B", "C"),
            ("C", "C"),
        )
        ```
    """

compress(*selectors)

Filter elements using a boolean selector iterable.

Stops when either the Iterator or selectors iterables have been exhausted

Parameters:

Name Type Description Default
*selectors bool

Boolean values indicating which elements to keep.

()

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the items selected by the boolean selectors.

Example
from pyochain import Iter, Seq

data = Seq("ABCDEF")
selectors = (1, 0, 1, 0, 1, 1)
expected = ("A", "C", "E", "F")
a = data.iter().compress(*selectors).collect(Seq)
assert a == expected
# Roughly equivalent to:
b = (
    data
    .iter()
    .zip(selectors)
    .filter_star(lambda _, selector: selector)
    .map_star(lambda x, _: x)
    .collect(Seq)
)
assert b == expected
Source code in pyochain/abc/_iterator.pyi
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
def compress(self, *selectors: bool) -> PyoIterator[T]:
    """Filter elements using a boolean selector iterable.

    Stops when either the `Iterator` or selectors iterables have been exhausted

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

    Returns:
        PyoIterator[T]: An `Iterator` of the items selected by the boolean selectors.

    Example:
        ```python
        from pyochain import Iter, Seq

        data = Seq("ABCDEF")
        selectors = (1, 0, 1, 0, 1, 1)
        expected = ("A", "C", "E", "F")
        a = data.iter().compress(*selectors).collect(Seq)
        assert a == expected
        # Roughly equivalent to:
        b = (
            data
            .iter()
            .zip(selectors)
            .filter_star(lambda _, selector: selector)
            .map_star(lambda x, _: x)
            .collect(Seq)
        )
        assert b == expected
        ```
    """

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)
assert data.count() == 3
# data is now empty
assert data.count() == 0
Source code in pyochain/abc/_iterator.pyi
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
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)
        assert data.count() == 3
        # data is now empty
        assert data.count() == 0
        ```
    """

cycle()

Yield elements from the Iterator endlessly, saving a copy of each call to next().

When the iterable is exhausted, return elements from the saved copy.

Thus, instead of stopping once all the elements have been yielded, the iterator will instead start again, from the beginning.

After iterating again, it will start at the beginning again. And again. And again. Forever.

Note that in case the original iterator is empty, the resulting iterator will also be empty.

You can use take or slice to limit the number of items taken.

See Also

repeat to create an Iterator from a single element repeatedly.

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: A new Iterator that cycles through the elements indefinitely.

Example
from pyochain import Seq

assert Seq(1, 2).iter().cycle().take(5).collect(Seq) == (1, 2, 1, 2, 1)
assert Seq("ABC").iter().cycle().take(5).join("") == "ABCAB"
Source code in pyochain/abc/_iterator.pyi
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
def cycle(self) -> PyoIterator[T]:
    """Yield elements from the `Iterator` endlessly, saving a copy of each call to `next()`.

    When the iterable is exhausted, return elements from the saved copy.

    Thus, instead of stopping once all the elements have been yielded, the iterator will instead start again, from the beginning.

    After iterating again, it will start at the beginning again. And again. And again. Forever.

    Note that in case the original iterator is empty, the resulting iterator will also be empty.

    You can use [`take`][] or [`slice`][] to limit the number of items taken.

    See Also:
        [`repeat`][] to create an `Iterator` from a single element repeatedly.

    Returns:
        PyoIterator[T]: A new `Iterator` that cycles through the elements indefinitely.

    Example:
        ```python
        from pyochain import Seq

        assert Seq(1, 2).iter().cycle().take(5).collect(Seq) == (1, 2, 1, 2, 1)
        assert Seq("ABC").iter().cycle().take(5).join("") == "ABCAB"
        ```
    """

enumerate(start=0)

Return a Iterator of (index, value) pairs.

Each value in the Iterator is paired with its index, starting from 0.

Tip

map_star[] can then be used for subsequent operations on the index and value.

This keep the code clean and readable, without index access like [0] and [1] for inline lambdas.

Parameters:

Name Type Description Default
start int

The starting index.

0

Returns:

Type Description
PyoIterator[tuple[int, T]]

PyoIterator[tuple[int, T]]: An Iterator of (index, value) pairs.

Example
from pyochain import Seq

data = Seq("apple", "banana", "cherry")
output = data.iter().enumerate().collect(Seq)
assert output == Seq((0, "apple"), (1, "banana"), (2, "cherry"))
output = (
    data
    .iter()
    .enumerate()
    .map_star(lambda idx, val: (idx, val.upper()))
    .collect(Seq)
)
assert output == Seq((0, "APPLE"), (1, "BANANA"), (2, "CHERRY"))
Source code in pyochain/abc/_iterator.pyi
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
def enumerate(self, start: int = 0) -> PyoIterator[tuple[int, T]]:
    """Return a `Iterator` of (index, value) pairs.

    Each value in the `Iterator` is paired with its index, starting from 0.

    Tip:
        `map_star`[] can then be used for subsequent operations on the index and value.

        This keep the code clean and readable, without index access like `[0]` and `[1]` for inline lambdas.

    Args:
        start (int): The starting index.

    Returns:
        PyoIterator[tuple[int, T]]: An `Iterator` of (index, value) pairs.

    Example:
        ```python
        from pyochain import Seq

        data = Seq("apple", "banana", "cherry")
        output = data.iter().enumerate().collect(Seq)
        assert output == Seq((0, "apple"), (1, "banana"), (2, "cherry"))
        output = (
            data
            .iter()
            .enumerate()
            .map_star(lambda idx, val: (idx, val.upper()))
            .collect(Seq)
        )
        assert output == Seq((0, "APPLE"), (1, "BANANA"), (2, "CHERRY"))
        ```
    """

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[object]

Another Iterable to compare against.

required

Returns:

Name Type Description
bool bool

True when both iterables yield the same sequence of values.

Example
from pyochain import Range, Seq

data = Range(1, 4)
assert data.iter().eq((1, 2, 3)) and data.iter().eq(data)
assert not data.iter().eq((1, 2, 4))
assert not data.iter().eq((1, 2))
Source code in pyochain/abc/_iterator.pyi
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
def eq(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Range, Seq

        data = Range(1, 4)
        assert data.iter().eq((1, 2, 3)) and data.iter().eq(data)
        assert not data.iter().eq((1, 2, 4))
        assert not data.iter().eq((1, 2))
        ```
    """

filter(func=None)

filter(func: None = None) -> PyoIterator[N]
filter(func: Callable[[T], TypeIs[R]]) -> PyoIterator[R]
filter(func: Callable[[T], TypeGuard[R]]) -> PyoIterator[R]
filter(
    func: Callable[[T], object] | None,
) -> PyoIterator[T]

Creates an Iterator with an optional closure to determine if an element should be yielded.

Given an element the closure must return True or False.

The returned Iterator will yield only the elements for which the closure returns True.

If no closure is provided, the elements are directly evaluated on their truthiness.

This means that empty collections, 0, False, and None will be filtered out.

The closure can return a TypeIs or TypeGuard to narrow the type of the returned Iterator.

This won't have any runtime effect, but allows for better type inference.

Note

.filter(f).next() is equivalent to .find(f).

See Also

filter_false for the complementary function that returns elements of the Iterator for which func is False.

Parameters:

Name Type Description Default
func FilterFn[T, R]

Function to evaluate each item.

None

Returns:

Type Description
PyoIterator[T] | PyoIterator[R]

PyoIterator[T] | PyoIterator[R]: An Iterator of the items that satisfy the predicate.

Example
from pyochain import Iter, Seq, Some

data = (1, 2, 3)
assert Iter(data).filter(lambda x: x > 1).collect(Seq) == Seq(2, 3)
# See the equivalence of next and find:
assert Iter(data).filter(lambda x: x > 1).next() == Some(2)
assert Iter(data).find(lambda x: x > 1) == Some(2)
# Using TypeIs to narrow type:
from typing import TypeIs

def _is_str(x: object) -> TypeIs[str]:
    return isinstance(x, str)

mixed_data = (1, "two", 3.0, "four")
assert Iter(mixed_data).filter(_is_str).collect(Seq) == Seq("two", "four")
maybe_none = (1, None, 3, None)
assert Iter(maybe_none).filter().collect(Seq) == Seq(1, 3)
maybe_false = (0, 1, False, 2, "", 3, None)
assert Iter(maybe_false).filter().collect(Seq) == Seq(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
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
def filter[R, N](
    self, func: FilterFn[T, R] = None
) -> PyoIterator[T] | PyoIterator[R]:
    """Creates an `Iterator` with an optional closure to determine if an element should be yielded.

    Given an element the closure must return `True` or `False`.

    The returned `Iterator` will yield only the elements for which the closure returns `True`.

    If no closure is provided, the elements are directly evaluated on their truthiness.

    This means that empty collections, `0`, `False`, and `None` will be filtered out.

    The closure can return a `TypeIs` or `TypeGuard` to narrow the type of the returned `Iterator`.

    This won't have any runtime effect, but allows for better type inference.

    Note:
        `.filter(f).next()` is equivalent to [`.find(f)`][find].

    See Also:
        [`filter_false`][] for the complementary function that returns elements of the `Iterator` for which *func* is `False`.

    Args:
        func (FilterFn[T, R]): Function to evaluate each item.

    Returns:
        PyoIterator[T] | PyoIterator[R]: An `Iterator` of the items that satisfy the predicate.

    Example:
        ```python
        from pyochain import Iter, Seq, Some

        data = (1, 2, 3)
        assert Iter(data).filter(lambda x: x > 1).collect(Seq) == Seq(2, 3)
        # See the equivalence of next and find:
        assert Iter(data).filter(lambda x: x > 1).next() == Some(2)
        assert Iter(data).find(lambda x: x > 1) == Some(2)
        # Using TypeIs to narrow type:
        from typing import TypeIs

        def _is_str(x: object) -> TypeIs[str]:
            return isinstance(x, str)

        mixed_data = (1, "two", 3.0, "four")
        assert Iter(mixed_data).filter(_is_str).collect(Seq) == Seq("two", "four")
        maybe_none = (1, None, 3, None)
        assert Iter(maybe_none).filter().collect(Seq) == Seq(1, 3)
        maybe_false = (0, 1, False, 2, "", 3, None)
        assert Iter(maybe_false).filter().collect(Seq) == Seq(1, 2, 3)
        ```
    """

filter_false(func=None)

filter_false(func: None = None) -> PyoIterator[None]
filter_false(
    func: Callable[[T], TypeIs[U]],
) -> PyoIterator[U]
filter_false(
    func: Callable[[T], TypeGuard[U]],
) -> PyoIterator[U]
filter_false(func: Callable[[T], object]) -> PyoIterator[T]

Return elements for which func predicate is False.

If no closure is provided, returns the elements who return False when calling __bool__ on them.

Parameters:

Name Type Description Default
func FilterFn[T, U]

Function to evaluate each item.

None

Returns:

Type Description
PyoIterator[T] | PyoIterator[U]

PyoIterator[T] | PyoIterator[U]: An Iterator of the items that do not satisfy the predicate.

Example
from pyochain import Seq, Range

a = Range(5).iter().filter_false(lambda x: x > 1).collect(Seq)
assert a == (0, 1)
b = Seq(1, 4, 6, 3, 8).iter().filter_false(lambda x: x < 5).collect(Seq)
assert b == Seq(6, 8)
# Count number of none values
assert Seq(1, None, 2, None, 3).iter().filter_false().count() == 2
Source code in pyochain/abc/_iterator.pyi
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
def filter_false[U](
    self, func: FilterFn[T, U] = None
) -> PyoIterator[T] | PyoIterator[U]:
    """Return elements for which **func** predicate is `False`.

    If no closure is provided, returns the elements who return `False` when calling `__bool__` on them.

    Args:
        func (FilterFn[T, U]): Function to evaluate each item.

    Returns:
        PyoIterator[T] | PyoIterator[U]: An `Iterator` of the items that do not satisfy the predicate.

    Example:
        ```python
        from pyochain import Seq, Range

        a = Range(5).iter().filter_false(lambda x: x > 1).collect(Seq)
        assert a == (0, 1)
        b = Seq(1, 4, 6, 3, 8).iter().filter_false(lambda x: x < 5).collect(Seq)
        assert b == Seq(6, 8)
        # Count number of none values
        assert Seq(1, None, 2, None, 3).iter().filter_false().count() == 2
        ```
    """

filter_map(func)

Creates an iterator that both filters and maps.

The returned iterator yields only the values for which the supplied closure returns Some(value).

filter_map can be used to make chains of filter and map more concise.

The example below shows how a map().filter().map() can be shortened to a single call to filter_map.

Parameters:

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

Function to apply to each item.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterable of the results where func returned Some.

See Also

filter with no closure provided if you want to filter out Python native None values.

Example
from pyochain import Result, Ok, Err, Seq

def _parse(s: str) -> Result[int, str]:
    try:
        return Ok(int(s))
    except ValueError:
        return Err(f"Invalid integer, got {s!r}")

data = Seq("1", "two", "NaN", "four", "5")
parsed = data.iter().filter_map(lambda s: _parse(s).ok()).collect(Seq)
assert parsed == Seq(1, 5)
# Equivalent to:
parsed = (
    data
    .iter()
    .map(lambda s: _parse(s).ok())
    .filter(lambda s: s.is_some())
    .map(lambda s: s.unwrap())
    .collect(Seq)
)
assert parsed == Seq(1, 5)
Source code in pyochain/abc/_iterator.pyi
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
def filter_map[R](self, func: Callable[[T], Option[R]]) -> PyoIterator[R]:
    """Creates an iterator that both filters and maps.

    The returned iterator yields only the values for which the supplied closure returns Some(value).

    `filter_map` can be used to make chains of `filter` and map more concise.

    The example below shows how a `map().filter().map()` can be shortened to a single call to `filter_map`.

    Args:
        func (Callable[[T], Option[R]]): Function to apply to each item.

    Returns:
        PyoIterator[R]: An iterable of the results where func returned `Some`.

    See Also:
        [`filter`][] with no closure provided if you want to filter out Python native `None` values.

    Example:
        ```python
        from pyochain import Result, Ok, Err, Seq

        def _parse(s: str) -> Result[int, str]:
            try:
                return Ok(int(s))
            except ValueError:
                return Err(f"Invalid integer, got {s!r}")

        data = Seq("1", "two", "NaN", "four", "5")
        parsed = data.iter().filter_map(lambda s: _parse(s).ok()).collect(Seq)
        assert parsed == Seq(1, 5)
        # Equivalent to:
        parsed = (
            data
            .iter()
            .map(lambda s: _parse(s).ok())
            .filter(lambda s: s.is_some())
            .map(lambda s: s.unwrap())
            .collect(Seq)
        )
        assert parsed == Seq(1, 5)
        ```
    """

filter_map_star(func)

filter_map_star(
    func: Callable[[Any], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2, T3], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2, T3, T4], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2, T3, T4, T5], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7], Option[R]],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8], Option[R]
    ],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9], Option[R]
    ],
) -> PyoIterator[R]
filter_map_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], Option[R]
    ],
) -> PyoIterator[R]

Creates an iterator that both filters and maps, where each element is an iterable.

Unlike .filter_map(), which passes each element as a single argument, .filter_map_star() unpacks each element into positional arguments for the function.

In short, for each element in the sequence, it computes func(*element).

This is useful after using methods like zip, product, or enumerate that yield tuples.

Parameters:

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

Function to apply to unpacked elements.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterable of the results where func returned Some.

Example
from pyochain import Result, Ok, Err, Seq

data = Seq(("1", "10"), ("two", "20"), ("3", "thirty"))

def _parse_pair(s1: str, s2: str) -> Result[tuple[int, int], str]:
    try:
        return Ok((int(s1), int(s2)))
    except ValueError:
        return Err(f"Invalid integer pair: {s1!r}, {s2!r}")

parsed = (
    data
    .iter()
    .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
    .collect(list)
)
assert parsed == [(1, 10)]
Source code in pyochain/abc/_iterator.pyi
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
def filter_map_star[U: Iterable[Any], R](
    self: PyoIterator[U], func: Callable[..., Option[R]]
) -> PyoIterator[R]:
    """Creates an iterator that both filters and maps, where each element is an iterable.

    Unlike `.filter_map()`, which passes each element as a single argument, `.filter_map_star()` unpacks each element into positional arguments for the function.

    In short, for each `element` in the sequence, it computes `func(*element)`.

    This is useful after using methods like `zip`, `product`, or `enumerate` that yield tuples.

    Args:
        func (Callable[..., Option[R]]): Function to apply to unpacked elements.

    Returns:
        PyoIterator[R]: An iterable of the results where func returned `Some`.

    Example:
        ```python
        from pyochain import Result, Ok, Err, Seq

        data = Seq(("1", "10"), ("two", "20"), ("3", "thirty"))

        def _parse_pair(s1: str, s2: str) -> Result[tuple[int, int], str]:
            try:
                return Ok((int(s1), int(s2)))
            except ValueError:
                return Err(f"Invalid integer pair: {s1!r}, {s2!r}")

        parsed = (
            data
            .iter()
            .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
            .collect(list)
        )
        assert parsed == [(1, 10)]
        ```
    """

filter_star(func)

filter_star(
    func: Callable[[T1], TypeIs[R]],
) -> PyoIterator[tuple[R]]
filter_star(
    func: Callable[[T1], TypeGuard[R]],
) -> PyoIterator[tuple[R]]
filter_star(
    func: Callable[[T1], object],
) -> PyoIterator[tuple[T1]]
filter_star(
    func: Callable[[T1, T2], TypeIs[tuple[R, R2]]],
) -> PyoIterator[tuple[R, R2]]
filter_star(
    func: Callable[[T1, T2], TypeGuard[tuple[R, R2]]],
) -> PyoIterator[tuple[R, R2]]
filter_star(
    func: Callable[[T1, T2], object],
) -> PyoIterator[tuple[T1, T2]]
filter_star(
    func: Callable[[T1, T2, T3], TypeIs[tuple[R, R2, R3]]],
) -> PyoIterator[tuple[R, R2, R3]]
filter_star(
    func: Callable[
        [T1, T2, T3], TypeGuard[tuple[R, R2, R3]]
    ],
) -> PyoIterator[tuple[R, R2, R3]]
filter_star(
    func: Callable[[T1, T2, T3], object],
) -> PyoIterator[tuple[T1, T2, T3]]
filter_star(
    func: Callable[[T1, T2, T3, T4], object],
) -> PyoIterator[tuple[T1, T2, T3, T4]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5], object],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], object],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7], object],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]]
filter_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8], object
    ],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]]
filter_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9], object
    ],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]]
filter_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], object
    ],
) -> PyoIterator[
    tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]
]

Creates an Iterator which uses a closure func to determine if an element should be yielded, where each element is an iterable.

Unlike .filter(), which passes each element as a single argument, .filter_star() unpacks each element into positional arguments for the func.

In short, for each element in the Iterator, it computes `func(*element)``.

This is useful after using methods like .zip(), .product(), or .enumerate() that yield tuples.

Parameters:

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

Function to evaluate unpacked elements.

required

Returns:

Type Description
PyoIterator[U]

PyoIterator[U]: An Iterator of the items that satisfy the predicate.

Example
from pyochain import Seq

data = Seq("apple", "banana", "cherry", "date")
output = (
    data
    .iter()
    .enumerate()
    .filter_star(lambda index, _: index % 2 == 0)
    .map_star(lambda _, fruit: fruit.title())
    .collect(Seq)
)
assert output == ("Apple", "Cherry")
Source code in pyochain/abc/_iterator.pyi
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
def filter_star[U: tuple[Any, ...]](
    self: PyoIterator[U], func: Callable[..., object]
) -> PyoIterator[U]:
    """Creates an `Iterator` which uses a closure **func** to determine if an element should be yielded, where each element is an iterable.

    Unlike `.filter()`, which passes each element as a single argument, `.filter_star()` unpacks each element into positional arguments for the **func**.

    In short, for each element in the `Iterator`, it computes `func(*element)``.

    This is useful after using methods like `.zip()`, `.product()`, or `.enumerate()` that yield tuples.

    Args:
        func (Callable[..., object]): Function to evaluate unpacked elements.

    Returns:
        PyoIterator[U]: An `Iterator` of the items that satisfy the predicate.

    Example:
        ```python
        from pyochain import Seq

        data = Seq("apple", "banana", "cherry", "date")
        output = (
            data
            .iter()
            .enumerate()
            .filter_star(lambda index, _: index % 2 == 0)
            .map_star(lambda _, fruit: fruit.title())
            .collect(Seq)
        )
        assert output == ("Apple", "Cherry")
        ```
    """

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 Range, Some

def gt_five(x: int) -> bool:
    return x > 5

def gt_nine(x: int) -> bool:
    return x > 9

data = Range(10)
assert data.iter().find(predicate=gt_five) == Some(6)
assert data.iter().find(predicate=gt_nine).unwrap_or("missing") == "missing"
Source code in pyochain/abc/_iterator.pyi
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
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 Range, Some

        def gt_five(x: int) -> bool:
            return x > 5

        def gt_nine(x: int) -> bool:
            return x > 9

        data = Range(10)
        assert data.iter().find(predicate=gt_five) == Some(6)
        assert data.iter().find(predicate=gt_nine).unwrap_or("missing") == "missing"
        ```
    """

find_map(func)

Applies function to the elements of the Iterator and returns the first Some(R) result.

Iter.find_map(f) is equivalent to Iter.filter_map(f).next().

Parameters:

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

Function to apply to each element, returning an Option[R].

required

Returns:

Type Description
Option[R]

Option[R]: The first Some(R) result from applying func, or NONE if no such result is found.

Example
from pyochain import Seq, Some, NONE, Option

def _parse(s: str) -> Option[int]:
    try:
        return Some(int(s))
    except ValueError:
        return NONE

assert Seq("lol", "NaN", "2", "5").iter().find_map(_parse) == Some(2)
Source code in pyochain/abc/_iterator.pyi
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
def find_map[R](self, func: Callable[[T], Option[R]]) -> Option[R]:
    """Applies function to the elements of the `Iterator` and returns the first Some(R) result.

    `Iter.find_map(f)` is equivalent to `Iter.filter_map(f).next()`.

    Args:
        func (Callable[[T], Option[R]]): Function to apply to each element, returning an `Option[R]`.

    Returns:
        Option[R]: The first `Some(R)` result from applying `func`, or `NONE` if no such result is found.

    Example:
        ```python
        from pyochain import Seq, Some, NONE, Option

        def _parse(s: str) -> Option[int]:
            try:
                return Some(int(s))
            except ValueError:
                return NONE

        assert Seq("lol", "NaN", "2", "5").iter().find_map(_parse) == Some(2)
        ```
    """

flat_map(func)

Creates an iterator that applies a function to each element of the original iterator and flattens the result.

This is useful when the func you want to pass to .map() itself returns an iterable, and you want to avoid having nested iterables in the output.

This is equivalent to calling .map(func).flatten().

Parameters:

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

Function to apply to each element.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterable of flattened transformed elements.

Example
from pyochain import Range, Seq

out = Range(1, 4).iter().flat_map(range).collect(Seq)
assert out == Seq(0, 0, 1, 0, 1, 2)
Source code in pyochain/abc/_iterator.pyi
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
def flat_map[R](self, func: Callable[[T], Iterable[R]]) -> PyoIterator[R]:
    """Creates an iterator that applies a function to each element of the original iterator and flattens the result.

    This is useful when the **func** you want to pass to `.map()` itself returns an iterable, and you want to avoid having nested iterables in the output.

    This is equivalent to calling `.map(func).flatten()`.

    Args:
        func (Callable[[T], Iterable[R]]): Function to apply to each element.

    Returns:
        PyoIterator[R]: An iterable of flattened transformed elements.

    Example:
        ```python
        from pyochain import Range, Seq

        out = Range(1, 4).iter().flat_map(range).collect(Seq)
        assert out == Seq(0, 0, 1, 0, 1, 2)
        ```
    """

flatten()

flatten() -> PyoIterator[U]
flatten() -> Never

Creates an Iterator that flattens nested structures.

This is useful when you have an Iterator of Iterable and you want to remove one level of indirection.

Returns:

Type Description
PyoIterator[U]

PyoIterator[U]: An Iterator of flattened elements.

Example

Basic usage:

from pyochain import Seq

data = Seq((1, 2, 3, 4), (5, 6))
flattened = data.iter().flatten().collect(Seq)
assert flattened == Seq(1, 2, 3, 4, 5, 6)
Mapping and then flattening:
words = Seq("he", "l", "lo!")
merged = words.iter().flatten().collect(Seq)
assert merged == Seq("h", "e", "l", "l", "o", "!")
Flattening only removes one level of nesting at a time:
d3 = Seq(((1, 2), (3, 4)), ((5, 6), (7, 8)))
d2 = d3.iter().flatten().collect(Seq)
assert d2 == Seq((1, 2), (3, 4), (5, 6), (7, 8))
d1 = d3.iter().flatten().flatten().collect(Seq)
assert d1 == Seq(1, 2, 3, 4, 5, 6, 7, 8)
Here we see that flatten() does not perform a “deep” flatten.

Instead, only one level of nesting is removed.

That is, if you flatten() a three-dimensional array, the result will be two-dimensional and not one-dimensional.

To get a one-dimensional structure, you have to flatten() again.

Source code in pyochain/abc/_iterator.pyi
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
def flatten[U](self: PyoIterator[Iterable[U]]) -> PyoIterator[U]:
    """Creates an `Iterator` that flattens nested structures.

    This is useful when you have an `Iterator` of `Iterable` and you want to remove one level of indirection.

    Returns:
        PyoIterator[U]: An `Iterator` of flattened elements.

    Example:
        Basic usage:
        ```python
        from pyochain import Seq

        data = Seq((1, 2, 3, 4), (5, 6))
        flattened = data.iter().flatten().collect(Seq)
        assert flattened == Seq(1, 2, 3, 4, 5, 6)
        ```
        Mapping and then flattening:
        ```python
        words = Seq("he", "l", "lo!")
        merged = words.iter().flatten().collect(Seq)
        assert merged == Seq("h", "e", "l", "l", "o", "!")
        ```
        Flattening only removes one level of nesting at a time:
        ```python
        d3 = Seq(((1, 2), (3, 4)), ((5, 6), (7, 8)))
        d2 = d3.iter().flatten().collect(Seq)
        assert d2 == Seq((1, 2), (3, 4), (5, 6), (7, 8))
        d1 = d3.iter().flatten().flatten().collect(Seq)
        assert d1 == Seq(1, 2, 3, 4, 5, 6, 7, 8)
        ```
        Here we see that `flatten()` does not perform a “deep” flatten.

        Instead, only **one** level of nesting is removed.

        That is, if you `flatten()` a three-dimensional array, the result will be two-dimensional and not one-dimensional.

        To get a one-dimensional structure, you have to `flatten()` again.

    """

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 Seq

data = Seq(1, 2, 3)

assert data.iter().fold(0, lambda acc, x: acc + x) == 6
assert data.iter().fold(10, lambda acc, x: acc + x) == 16
assert Seq("a", "b", "c").iter().fold("", lambda acc, x: acc + x) == "abc"
Source code in pyochain/abc/_iterator.pyi
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
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 Seq

        data = Seq(1, 2, 3)

        assert data.iter().fold(0, lambda acc, x: acc + x) == 6
        assert data.iter().fold(10, lambda acc, x: acc + x) == 16
        assert Seq("a", "b", "c").iter().fold("", lambda acc, x: acc + x) == "abc"
        ```
    """

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 reduce but with an initial value.

Example

from pyochain import Iter, Seq

data = Seq((1, 2), (3, 4))
assert data.iter().fold_star(0, lambda acc, x, y: acc + x + y) == 10
data = Seq(("a", "b"), ("c", "d"))
assert data.iter().fold_star("", lambda acc, x, y: acc + x + y) == "abcd"
You can also pass additional arguments to the folding function:
data = Seq((1, 2), (3, 4))

def add_with_offset(acc: int, x: int, y: int, offset: int) -> int:
    return acc + x + y + offset

assert data.iter().fold_star(0, add_with_offset, 10) == 30

Source code in pyochain/abc/_iterator.pyi
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
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 [`reduce`][] but with an initial value.

    Example:
        ```python
        from pyochain import Iter, Seq

        data = Seq((1, 2), (3, 4))
        assert data.iter().fold_star(0, lambda acc, x, y: acc + x + y) == 10
        data = Seq(("a", "b"), ("c", "d"))
        assert data.iter().fold_star("", lambda acc, x, y: acc + x + y) == "abcd"
        ```
        You can also pass additional arguments to the folding function:
        ```python
        data = Seq((1, 2), (3, 4))

        def add_with_offset(acc: int, x: int, y: int, offset: int) -> int:
            return acc + x + y + offset

        assert data.iter().fold_star(0, add_with_offset, 10) == 30
        ```
    """

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 Range, Vec

out = Vec()
Range(1, 4).iter().for_each(out.append)
assert out == Vec(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
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
def for_each[**P](
    self,
    func: Callable[Concatenate[T, P], Any],
    *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 Range, Vec

        out = Vec()
        Range(1, 4).iter().for_each(out.append)
        assert out == Vec(1, 2, 3)
        ```
    """

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 Range, Vec

vec = Vec()
Range(1, 5).iter().batched(2).for_each_star(lambda x, y: vec.append(x + y))
assert vec == Vec(3, 7)
Source code in pyochain/abc/_iterator.pyi
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
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 Range, Vec

        vec = Vec()
        Range(1, 5).iter().batched(2).for_each_star(lambda x, y: vec.append(x + y))
        assert vec == Vec(3, 7)
        ```
    """

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[object]

Another Iterable 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 Seq

data = Seq(1, 2, 3)

assert data.iter().ge((1, 2))
assert data.iter().ge(data)
assert not data.iter().ge((1, 2, 4))
Source code in pyochain/abc/_iterator.pyi
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
def ge(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)

        assert data.iter().ge((1, 2))
        assert data.iter().ge(data)
        assert not data.iter().ge((1, 2, 4))
        ```
    """

group_by(key=None)

group_by(
    key: None = None,
) -> PyoIterator[tuple[T, PyoIterator[T]]]
group_by(
    key: Callable[[T], K],
) -> PyoIterator[tuple[K, PyoIterator[T]]]
group_by(
    key: Callable[[T], K] | None = None,
) -> PyoIterator[
    tuple[K, PyoIterator[T]] | tuple[T, PyoIterator[T]]
]

Make an Iterator that returns consecutive keys and groups from the iterable.

The values yielded are (K, PyoIterator[T]) tuples, where the first element is the group key and the second element is an Iterator of type T over the group values.

The Iterator needs to already be sorted on the same key function.

This is due to the fact that it generates a new Group every time the value of the key function changes.

That behavior differs from SQL's GROUP BY which aggregates common elements regardless of their input order.

Warning

You must materialize the second element of the tuple immediately when iterating over groups.

Because .group_by() uses Python's itertools::groupby under the hood, each group's iterator shares internal state.

When you advance to the next group, the previous group's iterator becomes invalid and will yield empty results.

Parameters:

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

Function computing a key value for each element. If None, this defaults to an identity function and returns the element unchanged.

None

Returns:

Type Description
PyoIterator[tuple[Any | T, PyoIterator[T]]]

PyoIterator[tuple[Any | T, PyoIterator[T]]]: An Iterator of (key, value) tuples.

Example

Simple usage:

from pyochain import Seq

out = (
    Seq("AAAABBBCCDAABBB")
    .iter()
    .group_by()
    .map_star(lambda k, _: k)
    .collect(tuple)
)
assert out == ("A", "B", "C", "D", "A", "B")
out = (
    Seq("AAAABBBCCD")
    .iter()
    .group_by()
    .map_star(lambda _, g: g.collect(list))
    .collect(tuple)
)
assert out == (
    ["A", "A", "A", "A"],
    ["B", "B", "B"],
    ["C", "C"],
    ["D"],
)
group_by can let you compute complex operations very easily and efficiently.

For example, if we want to group even and odd numbers, we can do it like this:

from pyochain import Iter, Dict, Seq
from operator import itemgetter

# Example 1: Group even and odd numbers
res = (
    Iter
    .from_count()  # create an infinite iterator of integers
    .take(8)  # take the first 8
    .map(lambda x: (x % 2 == 0, x))  # map to (is_even, value)
    .sort_by(itemgetter(0))  # sort by is_even
    .iter()  # Since sort collect to a Vec, we need to convert back to Iter
    .group_by(itemgetter(0))  # group by is_even
    # extract values from groups, discarding keys, and materializing them
    .map_star(
        lambda g, vals: (g, vals.map_star(lambda _, y: y).collect(Seq))
    )
    .collect(Dict)
)
assert res == Dict({False: Seq(1, 3, 5, 7), True: Seq(0, 2, 4, 6)})
If we have a dataset who's items have a common key and who's already sorted by that key, we can easily perform grouped operations on it, like this:
from pyochain import Seq

data = Seq(
    {"name": "Alice", "gender": "F"},
    {"name": "Bob", "gender": "M"},
    {"name": "Charlie", "gender": "M"},
    {"name": "Dan", "gender": "M"},
)
# group by the gender key, and count the number of people in each group
output = (
    data
    .iter()
    .group_by(lambda x: x["gender"])
    .map_star(lambda g, vals: (g, vals.count()))
    .collect(Seq)
)
assert output == (("F", 1), ("M", 3))
However, you must be careful to materialize the group values immediately when iterating over groups, see below how the values of the groups are empty::
from pyochain import Seq

groups = (
    Seq("a1", "a2", "b1")
    .iter()
    .group_by(lambda x: x[0])
    .collect(Seq)
    .iter()
    .map_star(lambda g, vals: (g, vals.collect(Seq)))
    .collect(Seq)
)
assert groups == (("a", Seq()), ("b", Seq()))
As such, the correct pattern is the following:
from pyochain import Seq

groups = (
    Seq("a1", "a2", "b1", "b2")
    .iter()
    .group_by(lambda x: x[0])
    # ✅ Materialize NOW
    .map_star(lambda g, vals: (g, vals.collect(Seq)))
    .collect(Seq)
)
assert groups == (("a", Seq("a1", "a2")), ("b", Seq("b1", "b2")))

Source code in pyochain/abc/_iterator.pyi
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
def group_by(
    self,
    key: Callable[[T], Any] | None = None,
) -> PyoIterator[tuple[Any | T, PyoIterator[T]]]:
    """Make an `Iterator` that returns consecutive keys and groups from the iterable.

    The values yielded are `(K, PyoIterator[T])` tuples, where the first element is the group key and the second element is an `Iterator` of type `T` over the group values.

    The `Iterator` needs to already be sorted on the same key function.

    This is due to the fact that it generates a new `Group` every time the value of the **key** function changes.

    That behavior differs from SQL's `GROUP BY` which aggregates common elements regardless of their input order.

    Warning:
        You must materialize the second element of the tuple immediately when iterating over groups.

        Because `.group_by()` uses Python's `itertools::groupby` under the hood, each group's iterator shares internal state.

        When you advance to the next group, the previous group's iterator becomes invalid and will yield empty results.

    Args:
        key (Callable[[T], Any] | None): Function computing a key value for each element. If `None`, this defaults to an identity function and returns the element unchanged.

    Returns:
        PyoIterator[tuple[Any | T, PyoIterator[T]]]: An `Iterator` of `(key, value)` tuples.

    Example:
        Simple usage:
        ```python
        from pyochain import Seq

        out = (
            Seq("AAAABBBCCDAABBB")
            .iter()
            .group_by()
            .map_star(lambda k, _: k)
            .collect(tuple)
        )
        assert out == ("A", "B", "C", "D", "A", "B")
        out = (
            Seq("AAAABBBCCD")
            .iter()
            .group_by()
            .map_star(lambda _, g: g.collect(list))
            .collect(tuple)
        )
        assert out == (
            ["A", "A", "A", "A"],
            ["B", "B", "B"],
            ["C", "C"],
            ["D"],
        )
        ```
        `group_by` can let you compute complex operations very easily and efficiently.

        For example, if we want to group even and odd numbers, we can do it like this:
        ```python
        from pyochain import Iter, Dict, Seq
        from operator import itemgetter

        # Example 1: Group even and odd numbers
        res = (
            Iter
            .from_count()  # create an infinite iterator of integers
            .take(8)  # take the first 8
            .map(lambda x: (x % 2 == 0, x))  # map to (is_even, value)
            .sort_by(itemgetter(0))  # sort by is_even
            .iter()  # Since sort collect to a Vec, we need to convert back to Iter
            .group_by(itemgetter(0))  # group by is_even
            # extract values from groups, discarding keys, and materializing them
            .map_star(
                lambda g, vals: (g, vals.map_star(lambda _, y: y).collect(Seq))
            )
            .collect(Dict)
        )
        assert res == Dict({False: Seq(1, 3, 5, 7), True: Seq(0, 2, 4, 6)})
        ```
        If we have a dataset who's items have a common key and who's already sorted by that key, we can easily perform grouped operations on it, like this:
        ```python
        from pyochain import Seq

        data = Seq(
            {"name": "Alice", "gender": "F"},
            {"name": "Bob", "gender": "M"},
            {"name": "Charlie", "gender": "M"},
            {"name": "Dan", "gender": "M"},
        )
        # group by the gender key, and count the number of people in each group
        output = (
            data
            .iter()
            .group_by(lambda x: x["gender"])
            .map_star(lambda g, vals: (g, vals.count()))
            .collect(Seq)
        )
        assert output == (("F", 1), ("M", 3))
        ```
        However, you must be careful to materialize the group values immediately when iterating over groups, see below how the values of the groups are empty::
        ```python
        from pyochain import Seq

        groups = (
            Seq("a1", "a2", "b1")
            .iter()
            .group_by(lambda x: x[0])
            .collect(Seq)
            .iter()
            .map_star(lambda g, vals: (g, vals.collect(Seq)))
            .collect(Seq)
        )
        assert groups == (("a", Seq()), ("b", Seq()))
        ```
        As such, the correct pattern is the following:
        ```python
        from pyochain import Seq

        groups = (
            Seq("a1", "a2", "b1", "b2")
            .iter()
            .group_by(lambda x: x[0])
            # ✅ Materialize NOW
            .map_star(lambda g, vals: (g, vals.collect(Seq)))
            .collect(Seq)
        )
        assert groups == (("a", Seq("a1", "a2")), ("b", Seq("b1", "b2")))
        ```
    """

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[object]

Another Iterable to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly after other.

Example
from pyochain import Seq

data = Seq(1, 2, 3)
assert data.iter().gt((1, 2))
assert not data.iter().gt((1, 2, 9))
assert not data.iter().gt((1, 2, 3))
Source code in pyochain/abc/_iterator.pyi
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
def gt(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)
        assert data.iter().gt((1, 2))
        assert not data.iter().gt((1, 2, 9))
        assert not data.iter().gt((1, 2, 3))
        ```
    """

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 S

The element to interpose between items.

required

Returns:

Type Description
PyoIterator[S]

PyoIterator[S]: A new Iterator with the element interposed.

Example
from pyochain import Seq

data = Seq(1, 2, 3)
# Simple example with numbers
a = data.iter().intersperse(0).collect(Seq)
assert a == Seq(1, 0, 2, 0, 3)
# Useful when chaining with other operations
assert data.iter().intersperse(5).sum() == 16
# Inserting separators between groups, then flattening
a = (
    Seq((1, 2), (3, 4), (5, 6))
    .iter()
    .intersperse([-1])
    .flatten()
    .collect(Seq)
)
assert a == Seq(1, 2, -1, 3, 4, -1, 5, 6)
Source code in pyochain/abc/_iterator.pyi
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
def intersperse[S](self: PyoIterator[S], element: S) -> PyoIterator[S]:
    """Creates a new `Iterator` which places a copy of separator between adjacent items of the original iterator.

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

    Returns:
        PyoIterator[S]: A new `Iterator` with the element interposed.

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)
        # Simple example with numbers
        a = data.iter().intersperse(0).collect(Seq)
        assert a == Seq(1, 0, 2, 0, 3)
        # Useful when chaining with other operations
        assert data.iter().intersperse(5).sum() == 16
        # Inserting separators between groups, then flattening
        a = (
            Seq((1, 2), (3, 4), (5, 6))
            .iter()
            .intersperse([-1])
            .flatten()
            .collect(Seq)
        )
        assert a == Seq(1, 2, -1, 3, 4, -1, 5, 6)
        ```
    """

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

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

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

data = Seq(1, 2, 2)
assert data.iter().is_sorted()
assert not data.iter().is_sorted(strict=True)

Source code in pyochain/abc/_iterator.pyi
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
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:
        [`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

        assert Iter(1, 2, 3, 4, 5).is_sorted()
        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 2)
        assert data.iter().is_sorted()
        assert not data.iter().is_sorted(strict=True)
        ```
    """

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 Range, Seq

assert Range(1, 6).iter().map(str).is_sorted_by(int)
by_int = Seq(1, 5, 3).iter().map(str).is_sorted_by(int, reverse=True)
assert not by_int
If strict, tests for strict sorting, that is, returns False if equal elements are found:
from pyochain import Seq

data = Seq("1", "2", "2")
assert data.iter().is_sorted_by(int)
assert not data.iter().is_sorted_by(int, strict=True)

Source code in pyochain/abc/_iterator.pyi
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
def is_sorted_by(
    self,
    key: Callable[[T], SupportsComparison[Any]],
    *,
    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 Range, Seq

        assert Range(1, 6).iter().map(str).is_sorted_by(int)
        by_int = Seq(1, 5, 3).iter().map(str).is_sorted_by(int, reverse=True)
        assert not by_int
        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        from pyochain import Seq

        data = Seq("1", "2", "2")
        assert data.iter().is_sorted_by(int)
        assert not data.iter().is_sorted_by(int, strict=True)
        ```
    """

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

assert Iter("a", "b", "c").join("-") == "a-b-c"
Source code in pyochain/abc/_iterator.pyi
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
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

        assert Iter("a", "b", "c").join("-") == "a-b-c"
        ```
    """

last()

Consume the Iterator and return it's last element.

Warning

This will never return if the Iterator is infinite.

Returns:

Name Type Description
T T

The last element of the Iterator.

Example
from pyochain import Dict, Seq

data = Dict(a=1, b=2, c=3)
assert data.iter().last() == "c"
# If you have a `Sequence`, you can use `PyoSequence::last` instead, which is more efficient.
assert data.pipe(Seq).last() == "c"
Source code in pyochain/abc/_iterator.pyi
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
def last(self) -> T:
    """Consume the `Iterator` and return it's last element.

    Warning:
        This will never return if the `Iterator` is infinite.

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

    Example:
        ```python
        from pyochain import Dict, Seq

        data = Dict(a=1, b=2, c=3)
        assert data.iter().last() == "c"
        # If you have a `Sequence`, you can use `PyoSequence::last` instead, which is more efficient.
        assert data.pipe(Seq).last() == "c"
        ```
    """

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[object]

Another Iterable 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 Seq

data = Seq(1, 2, 3)
assert not data.iter().le((1, 2))
assert data.iter().le((1, 2, 3))
assert data.iter().le((1, 3))
Source code in pyochain/abc/_iterator.pyi
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
def le(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)
        assert not data.iter().le((1, 2))
        assert data.iter().le((1, 2, 3))
        assert data.iter().le((1, 3))
        ```
    """

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[object]

Another Iterable to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly before other.

Example
from pyochain import Seq

data = Seq(1, 2, 3)
assert not data.iter().lt((1, 2))
assert not data.iter().lt((1, 2, 3))
assert data.iter().lt((1, 3))
Source code in pyochain/abc/_iterator.pyi
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
def lt(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)
        assert not data.iter().lt((1, 2))
        assert not data.iter().lt((1, 2, 3))
        assert data.iter().lt((1, 3))
        ```
    """

map(func)

Apply a function func to each element of the Iterator.

If you are good at thinking in types, you can think of map like this:

  • You have an Iterator that gives you elements of some type A
  • You want an Iterator of some other type B
  • Thenyou can use .map(), passing a closure func that takes an A and returns a B.

map is conceptually similar to a for loop.

However, as map is lazy, it is best used when you are already working with other PyoIterator instances.

If you are doing some sort of looping for a side effect, it is considered more idiomatic to use for_each than map().collect(Seq).

Parameters:

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

Function to apply to each element.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterator of transformed elements.

Example
from pyochain import Seq

assert Seq(1, 2).iter().map(lambda x: x + 1).collect(Seq) == Seq(2, 3)
# You can use methods on the class rather than on instance for convenience:
data = Seq("a", "b", "c")

a = data.iter().map(str.upper).collect(Seq)
assert a == Seq("A", "B", "C")
b = data.iter().map(lambda s: s.upper()).collect(Seq)
assert b == Seq("A", "B", "C")
Source code in pyochain/abc/_iterator.pyi
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
def map[R](self, func: Callable[[T], R]) -> PyoIterator[R]:
    """Apply a function **func** to each element of the `Iterator`.

    If you are good at thinking in types, you can think of `map` like this:

    - You have an `Iterator` that gives you elements of some type `A`
    - You want an `Iterator` of some other type `B`
    - Thenyou can use `.map()`, passing a closure **func** that takes an `A` and returns a `B`.

    `map` is conceptually similar to a for loop.

    However, as `map` is lazy, it is best used when you are already working with other `PyoIterator` instances.

    If you are doing some sort of looping for a side effect, it is considered more idiomatic to use [`for_each`][] than `map().collect(Seq)`.

    Args:
        func (Callable[[T], R]): Function to apply to each element.

    Returns:
        PyoIterator[R]: An iterator of transformed elements.

    Example:
        ```python
        from pyochain import Seq

        assert Seq(1, 2).iter().map(lambda x: x + 1).collect(Seq) == Seq(2, 3)
        # You can use methods on the class rather than on instance for convenience:
        data = Seq("a", "b", "c")

        a = data.iter().map(str.upper).collect(Seq)
        assert a == Seq("A", "B", "C")
        b = data.iter().map(lambda s: s.upper()).collect(Seq)
        assert b == Seq("A", "B", "C")
        ```
    """

map_juxt(*funcs)

map_juxt(
    func1: Callable[[T], R1],
) -> PyoIterator[tuple[R1]]
map_juxt(
    func1: Callable[[T], R1], func2: Callable[[T], R2]
) -> PyoIterator[tuple[R1, R2]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
) -> PyoIterator[tuple[R1, R2, R3]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
) -> PyoIterator[tuple[R1, R2, R3, R4]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
) -> PyoIterator[tuple[R1, R2, R3, R4, R5]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
    func6: Callable[[T], R6],
) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
    func6: Callable[[T], R6],
    func7: Callable[[T], R7],
) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
    func6: Callable[[T], R6],
    func7: Callable[[T], R7],
    func8: Callable[[T], R8],
) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7, R8]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
    func6: Callable[[T], R6],
    func7: Callable[[T], R7],
    func8: Callable[[T], R8],
    func9: Callable[[T], R9],
) -> PyoIterator[tuple[R1, R2, R3, R4, R5, R6, R7, R8, R9]]
map_juxt(
    func1: Callable[[T], R1],
    func2: Callable[[T], R2],
    func3: Callable[[T], R3],
    func4: Callable[[T], R4],
    func5: Callable[[T], R5],
    func6: Callable[[T], R6],
    func7: Callable[[T], R7],
    func8: Callable[[T], R8],
    func9: Callable[[T], R9],
    func10: Callable[[T], R10],
) -> PyoIterator[
    tuple[R1, R2, R3, R4, R5, R6, R7, R8, R9, R10]
]
map_juxt(
    *funcs: Callable[[T], R],
) -> PyoIterator[tuple[R, ...]]

Apply several functions to each item of the Iterator.

Returns a new Iterator where each item is a tuple of the results of applying each function to the original item.

This can be very handy to compute multiple transformations or properties of the same item in a single pass, without needing to iterate multiple times.

As such, this can be considered as an alternative to various patterns, such as for_each and fold with mutable collections, or map followed by zip to combine the results.

Parameters:

Name Type Description Default
*funcs Callable[[T], Any]

Functions to apply to each item.

()

Returns:

Type Description
PyoIterator[tuple[Any, ...]]

PyoIterator[tuple[Any, ...]]: An Iterator of tuples containing the results of each function.

Example

from pyochain import Seq

def is_even(n: int) -> bool:
    return n % 2 == 0

def is_positive(n: int) -> bool:
    return n > 0

out = Seq(1, -2, 3).iter().map_juxt(is_even, is_positive).collect(Seq)
assert out == Seq((False, True), (True, False), (False, True))
If you need to pass additional args and kwargs to the functions, you can use functools::partial or create curried functions like this:
from pyochain import Range
from collections.abc import Callable

def curried_add(a: int) -> Callable[[int], int]:
    def fn(b: int) -> int:
        return a + b

    return fn

out = (
    Range(1, 4)
    .iter()
    .map_juxt(curried_add(10), curried_add(20))
    .collect(Seq)
)
assert out == Seq((11, 21), (12, 22), (13, 23))
You can then combine this with various other methods to perform complex transformations in a clean and efficient way, without needing to iterate multiple times or create intermediate collections.

Example with filter_star:

res = (
    Range(5)
    .iter()
    .map_juxt(lambda x: x * 2, lambda x: x**2)
    .filter_star(lambda double, square: double + square <= 5)
    .collect(Seq)
)
assert res == Seq((0, 0), (2, 1))

Source code in pyochain/abc/_iterator.pyi
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
def map_juxt(self, *funcs: Callable[[T], Any]) -> PyoIterator[tuple[Any, ...]]:
    """Apply several functions to each item of the `Iterator`.

    Returns a new `Iterator` where each item is a tuple of the results of applying each function to the original item.

    This can be very handy to compute multiple transformations or properties of the same item in a single pass, without needing to iterate multiple times.

    As such, this can be considered as an alternative to various patterns, such as [`for_each`][] and [`fold`][] with mutable collections, or [`map`][] followed by [`zip`][] to combine the results.

    Args:
        *funcs (Callable[[T], Any]): Functions to apply to each item.

    Returns:
        PyoIterator[tuple[Any, ...]]: An `Iterator` of tuples containing the results of each function.

    Example:
        ```python
        from pyochain import Seq

        def is_even(n: int) -> bool:
            return n % 2 == 0

        def is_positive(n: int) -> bool:
            return n > 0

        out = Seq(1, -2, 3).iter().map_juxt(is_even, is_positive).collect(Seq)
        assert out == Seq((False, True), (True, False), (False, True))
        ```
        If you need to pass additional args and kwargs to the functions, you can use `functools::partial` or create curried functions like this:
        ```python
        from pyochain import Range
        from collections.abc import Callable

        def curried_add(a: int) -> Callable[[int], int]:
            def fn(b: int) -> int:
                return a + b

            return fn

        out = (
            Range(1, 4)
            .iter()
            .map_juxt(curried_add(10), curried_add(20))
            .collect(Seq)
        )
        assert out == Seq((11, 21), (12, 22), (13, 23))
        ```
        You can then combine this with various other methods to perform complex transformations in a clean and efficient way, without needing to iterate multiple times or create intermediate collections.

        Example with `filter_star`:
        ```python
        res = (
            Range(5)
            .iter()
            .map_juxt(lambda x: x * 2, lambda x: x**2)
            .filter_star(lambda double, square: double + square <= 5)
            .collect(Seq)
        )
        assert res == Seq((0, 0), (2, 1))
        ```
    """

map_star(func)

map_star(func: Callable[[T1], R]) -> PyoIterator[R]
map_star(func: Callable[[T1, T2], R]) -> PyoIterator[R]
map_star(func: Callable[[T1, T2, T3], R]) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4], R],
) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4, T5], R],
) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], R],
) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
) -> PyoIterator[R]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
) -> PyoIterator[R]
map_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R
    ],
) -> PyoIterator[R]
map_star(func: Callable[..., R]) -> PyoIterator[R]
map_star(func: Callable[..., Any]) -> Never

Applies a function to each element.where each element is a tuple.

Unlike .map(), which passes each element as a single argument, .map_star() unpacks the tuple into positional arguments for the function.

In short, for each element in the Iterator, it computes func(*element).

This is strictly equivalent to itertools::starmap(func, self).

Note

Always prefer using .map_star() over .map() when working with Iterator of tuple elements.

Not only it is more readable, but it's also much more performant (up to 30% faster in benchmarks).

Parameters:

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

Function to apply to unpacked elements.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An Iterator of results from applying the function to unpacked elements.

Example
from pyochain import Seq

def make_sku(color: str, size: str) -> str:
    return f"{color}-{size}"

data = Seq("blue", "red")
a = data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
assert a == ("blue-S", "blue-M", "red-S", "red-M")
# This is equivalent to:
b = data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
assert b == ("blue-S", "blue-M", "red-S", "red-M")
Source code in pyochain/abc/_iterator.pyi
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
def map_star[R](
    self: PyoIterator[tuple[Any, ...]], func: Callable[..., R]
) -> PyoIterator[R]:
    """Applies a function to each element.where each element is a `tuple`.

    Unlike `.map()`, which passes each element as a single argument, `.map_star()` unpacks the tuple into positional arguments for the function.

    In short, for each element in the `Iterator`, it computes `func(*element)`.

    This is strictly equivalent to `itertools::starmap(func, self)`.

    Note:
        Always prefer using `.map_star()` over `.map()` when working with `Iterator` of `tuple` elements.

        Not only it is more readable, but it's also much more performant (up to 30% faster in benchmarks).

    Args:
        func (Callable[..., R]): Function to apply to unpacked elements.

    Returns:
        PyoIterator[R]: An `Iterator` of results from applying the function to unpacked elements.

    Example:
        ```python
        from pyochain import Seq

        def make_sku(color: str, size: str) -> str:
            return f"{color}-{size}"

        data = Seq("blue", "red")
        a = data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
        assert a == ("blue-S", "blue-M", "red-S", "red-M")
        # This is equivalent to:
        b = data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
        assert b == ("blue-S", "blue-M", "red-S", "red-M")
        ```
    """

map_while(func)

Creates an Iterator that both yields elements based on a predicate and maps.

map_while() takes a closure func as an argument.

It will call this closure on each element of the Iterator, and yield elements while it returns Some(_).

Parameters:

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

Function to apply to each element`.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An Iterator of transformed elements until NONE is encountered.

Examples:

Basic usage:

from pyochain import Vec, Some, NONE

a = Vec(-1, 4, 0, 1)

def checked_divide(x: int) -> Option[int]:
    if x == 0:
        return NONE
    return Some(16 // x)

iterator = a.iter().map_while(checked_divide)

assert iterator.next() == Some(-16)
assert iterator.next() == Some(4)
assert iterator.next().is_none()
Here's the same example, but with take_while and map:
a = Vec(-1, 4, 0, 1)

iterator = (
    a
    .iter()
    .map(checked_divide)
    .take_while(lambda x: x.is_some())
    .map(lambda x: x.unwrap())
)

assert iterator.next() == Some(-16)
assert iterator.next() == Some(4)
assert iterator.next().is_none()
Stopping after an initial None:
from pyochain import Result, Ok, Err

a = Vec(0, 1, 2, -3, 4, 5, -6)

def check_positive(x: int) -> Result[int, str]:
    if x < 0:
        return Err("Negative value cannot be converted to u32")
    return Ok(x)

iterator = a.iter().map_while(lambda x: check_positive(x).ok())
vec = iterator.collect(Vec)

# We have more elements that are positive (such as 4, 5),
# but `map_while` returned `NONE` for `-3` (as the `predicate` returned `None`).
assert vec == [0, 1, 2]
Because map_while() needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:
a = Vec(1, 2, -3, 4)
iterator = a.iter()

result = iterator.map_while(lambda n: u32_try_from(n).ok()).collect(Vec)

assert result == [1, 2]

result = iterator.collect(Vec)

assert result == [4]

The -3 is no longer there, because it was consumed in order to see if the iteration should stop, but wasn't placed back into the Iterator.

Source code in pyochain/abc/_iterator.pyi
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
def map_while[R](self, func: Callable[[T], Option[R]]) -> PyoIterator[R]:
    """Creates an `Iterator` that both yields elements based on a predicate and maps.

    `map_while()` takes a closure *func* as an argument.

    It will call this closure on each element of the `Iterator`, and yield elements while it returns `Some(_)`.

    Args:
        func (Callable[[T], Option[R]]): Function to apply to each element`.

    Returns:
        PyoIterator[R]: An `Iterator` of transformed elements until `NONE` is encountered.

    Examples:
        Basic usage:
        ```python
        from pyochain import Vec, Some, NONE

        a = Vec(-1, 4, 0, 1)

        def checked_divide(x: int) -> Option[int]:
            if x == 0:
                return NONE
            return Some(16 // x)

        iterator = a.iter().map_while(checked_divide)

        assert iterator.next() == Some(-16)
        assert iterator.next() == Some(4)
        assert iterator.next().is_none()
        ```
        Here's the same example, but with take_while and map:
        ```python
        a = Vec(-1, 4, 0, 1)

        iterator = (
            a
            .iter()
            .map(checked_divide)
            .take_while(lambda x: x.is_some())
            .map(lambda x: x.unwrap())
        )

        assert iterator.next() == Some(-16)
        assert iterator.next() == Some(4)
        assert iterator.next().is_none()
        ```
        Stopping after an initial None:
        ```python
        from pyochain import Result, Ok, Err

        a = Vec(0, 1, 2, -3, 4, 5, -6)

        def check_positive(x: int) -> Result[int, str]:
            if x < 0:
                return Err("Negative value cannot be converted to u32")
            return Ok(x)

        iterator = a.iter().map_while(lambda x: check_positive(x).ok())
        vec = iterator.collect(Vec)

        # We have more elements that are positive (such as 4, 5),
        # but `map_while` returned `NONE` for `-3` (as the `predicate` returned `None`).
        assert vec == [0, 1, 2]
        ```
        Because map_while() needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:
        ```
        a = Vec(1, 2, -3, 4)
        iterator = a.iter()

        result = iterator.map_while(lambda n: u32_try_from(n).ok()).collect(Vec)

        assert result == [1, 2]

        result = iterator.collect(Vec)

        assert result == [4]
        ```

        The -3 is no longer there, because it was consumed in order to see if the iteration should stop, but wasn't placed back into the `Iterator`.
    """

map_windows(length, func)

map_windows(
    length: Literal[1], func: Callable[[tuple[T]], R]
) -> PyoIterator[R]
map_windows(
    length: Literal[2], func: Callable[[tuple[T, T]], R]
) -> PyoIterator[R]
map_windows(
    length: Literal[3], func: Callable[[tuple[T, T, T]], R]
) -> PyoIterator[R]
map_windows(
    length: Literal[4],
    func: Callable[[tuple[T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[5],
    func: Callable[[tuple[T, T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[6],
    func: Callable[[tuple[T, T, T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[7],
    func: Callable[[tuple[T, T, T, T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[8],
    func: Callable[[tuple[T, T, T, T, T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[9],
    func: Callable[[tuple[T, T, T, T, T, T, T, T, T]], R],
) -> PyoIterator[R]
map_windows(
    length: Literal[10],
    func: Callable[
        [tuple[T, T, T, T, T, T, T, T, T, T]], R
    ],
) -> PyoIterator[R]
map_windows(
    length: int, func: Callable[[tuple[T, ...]], R]
) -> PyoIterator[R]

Calls the given func for each contiguous window of size length over self.

The windows during mapping overlaps.

The provided function is called with the entire window as a single tuple argument.

Parameters:

Name Type Description Default
length int

The length of each window.

required
func Callable[[tuple[Any, ...]], R]

Function to apply to each window.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterator over the outputs of func.

See Also

map_windows_star for a version that unpacks the window into separate arguments.

Example
from pyochain import Seq, Range
import statistics

data = Seq(1, 2, 3, 4)
means = data.iter().map_windows(2, statistics.mean).collect(Seq)
assert means == Seq(1.5, 2.5, 3.5)

joined = (
    Seq("abcd")
    .iter()
    .map_windows(3, lambda window: "".join(window).upper())
    .collect(Seq)
)
assert joined == Seq("ABC", "BCD")

sum_windows = Range(5).iter().map_windows(4, sum).collect(Seq)
assert sum_windows == Seq(6, 10)
Source code in pyochain/abc/_iterator.pyi
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
def map_windows[R](
    self,
    length: int,
    func: Callable[[tuple[Any, ...]], R],
) -> PyoIterator[R]:
    """Calls the given *func* for each contiguous window of size *length* over **self**.

    The windows during mapping overlaps.

    The provided function is called with the entire window as a single tuple argument.

    Args:
        length (int): The length of each window.
        func (Callable[[tuple[Any, ...]], R]): Function to apply to each window.

    Returns:
        PyoIterator[R]: An iterator over the outputs of func.

    See Also:
        [`map_windows_star`][] for a version that unpacks the window into separate arguments.

    Example:
        ```python
        from pyochain import Seq, Range
        import statistics

        data = Seq(1, 2, 3, 4)
        means = data.iter().map_windows(2, statistics.mean).collect(Seq)
        assert means == Seq(1.5, 2.5, 3.5)

        joined = (
            Seq("abcd")
            .iter()
            .map_windows(3, lambda window: "".join(window).upper())
            .collect(Seq)
        )
        assert joined == Seq("ABC", "BCD")

        sum_windows = Range(5).iter().map_windows(4, sum).collect(Seq)
        assert sum_windows == Seq(6, 10)
        ```
    """

map_windows_star(length, func)

map_windows_star(
    length: Literal[1], func: Callable[[T], R]
) -> PyoIterator[R]
map_windows_star(
    length: Literal[2], func: Callable[[T, T], R]
) -> PyoIterator[R]
map_windows_star(
    length: Literal[3], func: Callable[[T, T, T], R]
) -> PyoIterator[R]
map_windows_star(
    length: Literal[4], func: Callable[[T, T, T, T], R]
) -> PyoIterator[R]
map_windows_star(
    length: Literal[5], func: Callable[[T, T, T, T, T], R]
) -> PyoIterator[R]
map_windows_star(
    length: Literal[6],
    func: Callable[[T, T, T, T, T, T], R],
) -> PyoIterator[R]
map_windows_star(
    length: Literal[7],
    func: Callable[[T, T, T, T, T, T, T], R],
) -> PyoIterator[R]
map_windows_star(
    length: Literal[8],
    func: Callable[[T, T, T, T, T, T, T, T], R],
) -> PyoIterator[R]
map_windows_star(
    length: Literal[9],
    func: Callable[[T, T, T, T, T, T, T, T, T], R],
) -> PyoIterator[R]
map_windows_star(
    length: Literal[10],
    func: Callable[[T, T, T, T, T, T, T, T, T, T], R],
) -> PyoIterator[R]

Calls the given func for each contiguous window of size length over self.

The windows during mapping overlaps.

The provided function is called with each element of the window as separate arguments.

Parameters:

Name Type Description Default
length int

The length of each window.

required
func Callable[..., R]

Function to apply to each window.

required

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An iterator over the outputs of func.

See Also

map_windows for a version that passes the entire window as a single tuple argument.

Example
from pyochain import Seq, Iter

a = Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
assert a == Seq("a+b", "b+c", "c+d")
b = (
    Seq(1, 2, 3, 4)
    .iter()
    .map_windows_star(2, lambda x, y: x + y)
    .collect(Seq)
)
assert b == Seq(3, 5, 7)
Source code in pyochain/abc/_iterator.pyi
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
def map_windows_star[R](
    self, length: int, func: Callable[..., R]
) -> PyoIterator[R]:
    """Calls the given *func* for each contiguous window of size *length* over **self**.

    The windows during mapping overlaps.

    The provided function is called with each element of the window as separate arguments.

    Args:
        length (int): The length of each window.
        func (Callable[..., R]): Function to apply to each window.

    Returns:
        PyoIterator[R]: An iterator over the outputs of func.

    See Also:
        [`map_windows`][] for a version that passes the entire window as a single tuple argument.

    Example:
        ```python
        from pyochain import Seq, Iter

        a = Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
        assert a == Seq("a+b", "b+c", "c+d")
        b = (
            Seq(1, 2, 3, 4)
            .iter()
            .map_windows_star(2, lambda x, y: x + y)
            .collect(Seq)
        )
        assert b == Seq(3, 5, 7)
        ```
    """

map_with(func, *iterables)

map_with(
    func: Callable[[T, T1], R], iterable: Iterable[T1]
) -> PyoIterator[R]
map_with(
    func: Callable[[T, T1, T2], R],
    iterable: Iterable[T1],
    iter2: Iterable[T2],
) -> PyoIterator[R]
map_with(
    func: Callable[[T, T1, T2, T3], R],
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
) -> PyoIterator[R]
map_with(
    func: Callable[[T, T1, T2, T3, T4], R],
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
) -> PyoIterator[R]
map_with(
    func: Callable[[T, T1, T2, T3, T4, T5], R],
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
) -> PyoIterator[R]
map_with(
    func: Callable[[T, T1, T2, T3, T4, T5, T6], R],
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
) -> PyoIterator[R]

Applies a function to the elements of this Iterator and additional iterables.

The provided function must take as many arguments as the number of iterables provided (including self).

It is then applied to the items from all iterables in parallel.

The Iterator stops when the shortest iterable is exhausted.

Parameters:

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

Function to apply to the elements of the iterables.

required
*iterables Iterable[Any]

Additional iterables to zip with self.

()

Returns:

Type Description
PyoIterator[R]

PyoIterator[R]: An Iterator of results from applying the function to the elements of the iterables.

See Also

map_juxt to apply multiple functions to the same elements of the Iterator.

Example
from pyochain import Seq
from dataclasses import dataclass

@dataclass
class Triangle:
    x: int
    y: int
    z: int

x = Seq(1, 2, 3)
y = [4, 5, 6]
z = [7, 8, 9]
output = x.iter().map_with(Triangle, y, z).collect(Seq)
assert output == Seq(
    Triangle(x=1, y=4, z=7),
    Triangle(x=2, y=5, z=8),
    Triangle(x=3, y=6, z=9),
)
output_2 = x.iter().map_with(lambda a, b, c: a + b + c, y, z).collect(Seq)
assert output_2 == Seq(12, 15, 18)
Source code in pyochain/abc/_iterator.pyi
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
def map_with[R](
    self, func: Callable[..., R], *iterables: Iterable[Any]
) -> PyoIterator[R]:
    """Applies a function to the elements of this `Iterator` and additional iterables.

    The provided function must take as many arguments as the number of iterables provided (including **self**).

    It is then applied to the items from all iterables in parallel.

    The `Iterator` stops when the shortest iterable is exhausted.

    Args:
        func (Callable[..., R]): Function to apply to the elements of the iterables.
        *iterables (Iterable[Any]): Additional iterables to zip with **self**.

    Returns:
        PyoIterator[R]: An `Iterator` of results from applying the function to the elements of the iterables.

    See Also:
        [`map_juxt`][] to apply multiple functions to the same elements of the `Iterator`.

    Example:
        ```python
        from pyochain import Seq
        from dataclasses import dataclass

        @dataclass
        class Triangle:
            x: int
            y: int
            z: int

        x = Seq(1, 2, 3)
        y = [4, 5, 6]
        z = [7, 8, 9]
        output = x.iter().map_with(Triangle, y, z).collect(Seq)
        assert output == Seq(
            Triangle(x=1, y=4, z=7),
            Triangle(x=2, y=5, z=8),
            Triangle(x=3, y=6, z=9),
        )
        output_2 = x.iter().map_with(lambda a, b, c: a + b + c, y, z).collect(Seq)
        assert output_2 == Seq(12, 15, 18)
        ```
    """

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 Seq

assert Seq(3, 1, 2).iter().max() == 3
Source code in pyochain/abc/_iterator.pyi
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
def max[U: SupportsRichComparison](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`][] 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 Seq

        assert Seq(3, 1, 2).iter().max() == 3
        ```
    """

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)

assert persons.iter().max_by(lambda p: p.age).name == "Alice"
assert persons.iter().max_by(lambda p: p.name).name == "Charlie"
assert persons.iter().max_by(Person.get_discount).name == "Bob"
Source code in pyochain/abc/_iterator.pyi
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
def max_by[U: SupportsRichComparison](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)

        assert persons.iter().max_by(lambda p: p.age).name == "Alice"
        assert persons.iter().max_by(lambda p: p.name).name == "Charlie"
        assert persons.iter().max_by(Person.get_discount).name == "Bob"
        ```
    """

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 Seq

assert Seq(3, 1, 2).iter().min() == 1
Source code in pyochain/abc/_iterator.pyi
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
def min[U: SupportsRichComparison](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 Seq

        assert Seq(3, 1, 2).iter().min() == 1
        ```
    """

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)

assert persons.iter().min_by(lambda p: p.age).name == "Bob"
assert persons.iter().min_by(lambda p: p.name).name == "Alice"
assert persons.iter().min_by(Person.get_discount).name == "Alice"
Source code in pyochain/abc/_iterator.pyi
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
def min_by[U: SupportsRichComparison](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)

        assert persons.iter().min_by(lambda p: p.age).name == "Bob"
        assert persons.iter().min_by(lambda p: p.name).name == "Alice"
        assert persons.iter().min_by(Person.get_discount).name == "Alice"
        ```
    """

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[object]

Another Iterable to compare against.

required

Returns:

Name Type Description
bool bool

True when the two iterables are not equal.

Example
from pyochain import Range

data = Range(1, 4)

assert not data.iter().ne((1, 2, 3))
assert data.iter().ne((1, 2, 4))
assert data.iter().ne((1, 2))
Source code in pyochain/abc/_iterator.pyi
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
def ne(self, other: Iterable[object]) -> 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[object]): Another `Iterable` to compare against.

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

    Example:
        ```python
        from pyochain import Range

        data = Range(1, 4)

        assert not data.iter().ne((1, 2, 3))
        assert data.iter().ne((1, 2, 4))
        assert data.iter().ne((1, 2))
        ```
    """

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.

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, Some, Null

it = Seq(1, 2, 3).iter()
assert it.next() == Some(1)
assert it.next() == Some(2)
assert it.next() == Some(3)
# iterator is now exhausted
assert it.next() is Null()
Source code in pyochain/abc/_iterator.pyi
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
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.

    `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, Some, Null

        it = Seq(1, 2, 3).iter()
        assert it.next() == Some(1)
        assert it.next() == Some(2)
        assert it.next() == Some(3)
        # iterator is now exhausted
        assert it.next() is Null()
        ```
    """

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. It must be a non-negative integer.

required

Returns:

Type Description
Option[T]

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

Example
from pyochain import Range

data = Range(10)
assert data.iter().nth(1).unwrap() == 1
assert data.iter().nth(10).is_none()
Source code in pyochain/abc/_iterator.pyi
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
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. It must be a non-negative integer.

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

    Example:
        ```python
        from pyochain import Range

        data = Range(10)
        assert data.iter().nth(1).unwrap() == 1
        assert data.iter().nth(10).is_none()
        ```
    """

pairwise()

Return successive overlapping pairs from the Iterator.

The number of 2-tuples in the resulting Iterator will be one fewer than the number of inputs.

It will be empty if the current Iterator has fewer than two values.

Returns:

Type Description
PyoIterator[tuple[T, T]]

PyoIterator[tuple[T, T]]: An Iterator of pairs of consecutive elements.

Example
from pyochain import Seq

assert Seq(1, 2, 3).iter().pairwise().collect(Seq) == ((1, 2), (2, 3))
assert Seq("ABCDEFG").iter().pairwise().collect(Seq) == (
    ("A", "B"),
    ("B", "C"),
    ("C", "D"),
    ("D", "E"),
    ("E", "F"),
    ("F", "G"),
)
Source code in pyochain/abc/_iterator.pyi
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
def pairwise(self) -> PyoIterator[tuple[T, T]]:
    """Return successive overlapping pairs from the `Iterator`.

    The number of 2-tuples in the resulting `Iterator` will be one fewer than the number of inputs.

    It will be empty if the current `Iterator` has fewer than two values.

    Returns:
        PyoIterator[tuple[T, T]]: An `Iterator` of pairs of consecutive elements.

    Example:
        ```python
        from pyochain import Seq

        assert Seq(1, 2, 3).iter().pairwise().collect(Seq) == ((1, 2), (2, 3))
        assert Seq("ABCDEFG").iter().pairwise().collect(Seq) == (
            ("A", "B"),
            ("B", "C"),
            ("C", "D"),
            ("D", "E"),
            ("E", "F"),
            ("F", "G"),
        )
        ```
    """

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[[S], bool]

Function to determine partition boundaries.

required

Returns:

Type Description
tuple[Vec[S], Vec[S]]

tuple[Vec[S], Vec[S]]: The resulting pair of collections

Example
from pyochain import Vec, Range

a, b = Range(1, 6).iter().partition(lambda x: x % 2 == 0)
assert a == Vec(2, 4)
assert b == Vec(1, 3, 5)
Source code in pyochain/abc/_iterator.pyi
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
def partition[S](
    self: PyoIterable[S], predicate: Callable[[S], bool]
) -> tuple[Vec[S], Vec[S]]:
    """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[[S], bool]): Function to determine partition boundaries.

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

    Example:
        ```python
        from pyochain import Vec, Range

        a, b = Range(1, 6).iter().partition(lambda x: x % 2 == 0)
        assert a == Vec(2, 4)
        assert b == Vec(1, 3, 5)
        ```
    """

peekable()

Creates an iterator which can use the peek and peek_mut methods to look at the next element of the Iterator without consuming it.

See their documentation for more information.

Note that the underlying Iterator is still advanced when peek or peek_mut are called for the first time.

In order to retrieve the next element, next is called on the underlying Iterator, hence any side effects (i.e. anything other than fetching the next value) of the next method will occur.

Returns:

Type Description
Peekable[S]

Peekable[S]: A new Iterator that allows peeking at the next element.

Examples:

Basic usage:

from pyochain import Range, Some

xs = Range(1, 4)
iterator = xs.iter().peekable()

# peek() lets us see into the future
assert iterator.peek() == Some(1)
assert iterator.next() == Some(1)
assert iterator.next() == Some(2)

# we can peek() multiple times, the iterator won't advance
assert iterator.peek() == Some(3)
assert iterator.peek() == Some(3)
assert iterator.next() == Some(3)

# after the iterator is finished, so is peek()
assert iterator.peek().is_none()
assert iterator.next().is_none()

Source code in pyochain/abc/_iterator.pyi
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
def peekable[S](self: PyoIterator[S]) -> Peekable[S]:
    """Creates an iterator which can use the peek and peek_mut methods to look at the next element of the `Iterator` without consuming it.

    See their documentation for more information.

    Note that the underlying `Iterator` is still advanced when peek or peek_mut are called for the first time.

    In order to retrieve the next element, `next` is called on the underlying `Iterator`, hence any side effects (i.e. anything other than fetching the next value) of the `next` method will occur.

    Returns:
        Peekable[S]: A new `Iterator` that allows peeking at the next element.

    Examples:
        Basic usage:
        ```python
        from pyochain import Range, Some

        xs = Range(1, 4)
        iterator = xs.iter().peekable()

        # peek() lets us see into the future
        assert iterator.peek() == Some(1)
        assert iterator.next() == Some(1)
        assert iterator.next() == Some(2)

        # we can peek() multiple times, the iterator won't advance
        assert iterator.peek() == Some(3)
        assert iterator.peek() == Some(3)
        assert iterator.next() == Some(3)

        # after the iterator is finished, so is peek()
        assert iterator.peek().is_none()
        assert iterator.next().is_none()
        ```
    """

permutations(r=None)

permutations(r: Literal[2]) -> PyoIterator[tuple[T, T]]
permutations(r: Literal[3]) -> PyoIterator[tuple[T, T, T]]
permutations(
    r: Literal[4],
) -> PyoIterator[tuple[T, T, T, T]]
permutations(
    r: Literal[5],
) -> PyoIterator[tuple[T, T, T, T, T]]

Return successive r length permutations of elements from the Iterator.

The output is a subsequence of product() where entries with repeated elements have been filtered out.

The length of the output is given by math.perm() which computes:

n! / (n - r)! when 0 ≤ r ≤ n or zero when r > n.

The permutation tuples are emitted in lexicographic order according to the order of the current Iterator, i.e Self.

If Self is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value.

If Self elements are unique, there will be no repeated values within a permutation.

Parameters:

Name Type Description Default
r int | None

Length of each permutation. If not specified or None, defaults to the length of Self, and all possible full-length permutations are generated.

None

Returns:

Type Description
PyoIterator[tuple[T, ...]]

PyoIterator[tuple[T, ...]]: An Iterator of permutations.

Example
from pyochain import Seq, Range

a = Seq(1, 2, 3).iter().permutations(2).collect(Seq)
assert a == ((1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2))

b = Range(3).iter().permutations().collect(Seq)
assert b == (
    (0, 1, 2),
    (0, 2, 1),
    (1, 0, 2),
    (1, 2, 0),
    (2, 0, 1),
    (2, 1, 0),
)
Source code in pyochain/abc/_iterator.pyi
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
def permutations(self, r: int | None = None) -> PyoIterator[tuple[T, ...]]:
    """Return successive *r* length permutations of elements from the `Iterator`.

    The output is a subsequence of `product()` where entries with repeated elements have been filtered out.

    The length of the output is given by `math.perm()` which computes:

    `n! / (n - r)! when 0 ≤ r ≤ n or zero when r > n.`

    The permutation tuples are emitted in lexicographic order according to the order of the current `Iterator`, i.e `Self`.

    If `Self` is sorted, the output tuples will be produced in sorted order.

    Elements are treated as unique based on their position, not on their value.

    If `Self` elements are unique, there will be no repeated values within a permutation.

    Args:
        r (int | None): Length of each permutation. If not specified or `None`, defaults to the length of `Self`, and all possible full-length permutations are generated.

    Returns:
        PyoIterator[tuple[T, ...]]: An `Iterator` of permutations.

    Example:
        ```python
        from pyochain import Seq, Range

        a = Seq(1, 2, 3).iter().permutations(2).collect(Seq)
        assert a == ((1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2))

        b = Range(3).iter().permutations().collect(Seq)
        assert b == (
            (0, 1, 2),
            (0, 2, 1),
            (1, 0, 2),
            (1, 2, 0),
            (2, 0, 1),
            (2, 1, 0),
        )
        ```
    """

product(*iterables, repeat=1)

product() -> PyoIterator[tuple[T]]
product(iter2: Iterable[T2]) -> PyoIterator[tuple[T, T2]]
product(
    iter2: Iterable[T2], iter3: Iterable[T3]
) -> PyoIterator[tuple[T, T2, T3]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
) -> PyoIterator[tuple[T, T2, T3, T4]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
) -> PyoIterator[tuple[T, T2, T3, T4, T5]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
    iter7: Iterable[T7],
) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
    iter7: Iterable[T7],
    iter8: Iterable[T8],
) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7, T8]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
    iter7: Iterable[T7],
    iter8: Iterable[T8],
    iter9: Iterable[T9],
) -> PyoIterator[tuple[T, T2, T3, T4, T5, T6, T7, T8, T9]]
product(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    iter6: Iterable[T6],
    iter7: Iterable[T7],
    iter8: Iterable[T8],
    iter9: Iterable[T9],
    iter10: Iterable[T10],
) -> PyoIterator[
    tuple[T, T2, T3, T4, T5, T6, T7, T8, T9, T10]
]
product(
    *iterables: Iterable[S], repeat: int = ...
) -> PyoIterator[tuple[S, ...]]

Computes the Cartesian product with other Iterable.

Roughly equivalent to nested for-loops as an Iterator method.

from pyochain import Iter

assert Iter.once("A").iter().product("B").collect(tuple) == tuple(
    (x, y) for x in "A" for y in "B"
)

The nested loops cycle like an odometer with the rightmost element advancing on every iteration.

This pattern creates a lexicographic ordering so that if the input iterables are sorted, the product tuples are emitted in sorted order.

To compute the product of the current Iterator with itself, specify the number of repetitions with the optional repeat keyword argument.

from pyochain import Seq

x = Seq(["A"])
a = x.iter().product(repeat=4).collect(Seq)
b = x.iter().product(x, x, x).collect(Seq)
assert a == b
Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products.

Accordingly, it is only useful with finite inputs.

Parameters:

Name Type Description Default
*iterables Iterable[Any]

Other iterables to compute the Cartesian product with.

()
repeat int

The number of repetitions of the Cartesian product.

1

Returns:

Type Description
PyoIterator[tuple[Any, ...]]

PyoIterator[tuple[Any, ...]]: An iterable of tuples containing elements from the Cartesian product.

Example
from pyochain import Seq, Range, Iter

colors = Seq("blue", "red")
sizes = Seq("S", "M")
a = colors.iter().product(sizes).collect(Seq)
assert a == (("blue", "S"), ("blue", "M"), ("red", "S"), ("red", "M"))
b = (
    colors
    .iter()
    .product(sizes)
    .map_star(lambda color, size: f"{color}-{size}")
    .collect(Seq)
)
assert b == ("blue-S", "blue-M", "red-S", "red-M")
c = (
    Range(1, 4)
    .iter()
    .product((10, 20))
    .filter_star(lambda a, b: a * b >= 40)
    .collect(Seq)
)
assert c == ((2, 20), (3, 20))
d = (
    Seq(26, 33)
    .iter()
    .product(("Michael", "Sophie"), ["Engineer"])
    .map_star(
        lambda age, name, profession: f"{name} is {age} and is {profession}"
    )
    .collect(tuple)
)
assert d == (
    "Michael is 26 and is Engineer",
    "Sophie is 26 and is Engineer",
    "Michael is 33 and is Engineer",
    "Sophie is 33 and is Engineer",
)
e = Seq("blue", "red").iter().product(repeat=2).collect(Seq)
assert e == (
    ("blue", "blue"),
    ("blue", "red"),
    ("red", "blue"),
    ("red", "red"),
)
Source code in pyochain/abc/_iterator.pyi
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
def product(
    self, *iterables: Iterable[Any], repeat: int = 1
) -> PyoIterator[tuple[Any, ...]]:
    """Computes the Cartesian product with other `Iterable`.

    Roughly equivalent to nested for-loops as an `Iterator` method.

    ```python
    from pyochain import Iter

    assert Iter.once("A").iter().product("B").collect(tuple) == tuple(
        (x, y) for x in "A" for y in "B"
    )
    ```

    The nested loops cycle like an odometer with the rightmost element advancing on every iteration.

    This pattern creates a lexicographic ordering so that if the input iterables are sorted, the product tuples are emitted in sorted order.

    To compute the product of the current `Iterator` with itself, specify the number of repetitions with the optional repeat keyword argument.

    ```python
    from pyochain import Seq

    x = Seq(["A"])
    a = x.iter().product(repeat=4).collect(Seq)
    b = x.iter().product(x, x, x).collect(Seq)
    assert a == b
    ```
    Before `product()` runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products.

    Accordingly, it is only useful with finite inputs.

    Args:
        *iterables (Iterable[Any]): Other iterables to compute the Cartesian product with.
        repeat (int): The number of repetitions of the Cartesian product.

    Returns:
        PyoIterator[tuple[Any, ...]]: An iterable of tuples containing elements from the Cartesian product.

    Example:
        ```python
        from pyochain import Seq, Range, Iter

        colors = Seq("blue", "red")
        sizes = Seq("S", "M")
        a = colors.iter().product(sizes).collect(Seq)
        assert a == (("blue", "S"), ("blue", "M"), ("red", "S"), ("red", "M"))
        b = (
            colors
            .iter()
            .product(sizes)
            .map_star(lambda color, size: f"{color}-{size}")
            .collect(Seq)
        )
        assert b == ("blue-S", "blue-M", "red-S", "red-M")
        c = (
            Range(1, 4)
            .iter()
            .product((10, 20))
            .filter_star(lambda a, b: a * b >= 40)
            .collect(Seq)
        )
        assert c == ((2, 20), (3, 20))
        d = (
            Seq(26, 33)
            .iter()
            .product(("Michael", "Sophie"), ["Engineer"])
            .map_star(
                lambda age, name, profession: f"{name} is {age} and is {profession}"
            )
            .collect(tuple)
        )
        assert d == (
            "Michael is 26 and is Engineer",
            "Sophie is 26 and is Engineer",
            "Michael is 33 and is Engineer",
            "Sophie is 33 and is Engineer",
        )
        e = Seq("blue", "red").iter().product(repeat=2).collect(Seq)
        assert e == (
            ("blue", "blue"),
            ("blue", "red"),
            ("red", "blue"),
            ("red", "red"),
        )
        ```
    """

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[[S, S], S]

Function to apply cumulatively to the items of the iterable.

required

Returns:

Name Type Description
S S

Single value resulting from cumulative reduction.

Example
from pyochain import Range

assert Range(1, 4).iter().reduce(lambda a, b: a + b) == 6
Source code in pyochain/abc/_iterator.pyi
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
def reduce[S](self: PyoIterator[S], func: Callable[[S, S], S]) -> S:
    """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[[S, S], S]): Function to apply cumulatively to the items of the iterable.

    Returns:
        S: Single value resulting from cumulative reduction.

    Example:
        ```python
        from pyochain import Range

        assert Range(1, 4).iter().reduce(lambda a, b: a + b) == 6
        ```
    """

scan(initial, func)

Transform elements by sharing state between iterations.

scan takes two arguments:

- an **initial** value which seeds the internal state
- a **func** with two arguments

The first being a reference to the internal state and the second an iterator element.

The func can assign to the internal state to share state between iterations.

On iteration, the func will be applied to each element of the iterator and the return value from the func, an Option, is returned by the next method.

Thus the func can return Some(value) to yield value, or NONE to end the iteration.

Parameters:

Name Type Description Default
initial U

Initial state.

required
func Callable[[U, T], Option[U]]

Function that takes the current state and an item, and returns an Option.

required

Returns:

Type Description
PyoIterator[U]

PyoIterator[U]: An iterable of the yielded values.

Example
from pyochain import Some, NONE, Range, Seq, Option

def accumulate_until_limit(state: int, item: int) -> Option[int]:
    new_state = state + item
    match new_state:
        case _ if new_state <= 10:
            return Some(new_state)
        case _:
            return NONE

out = Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
assert out == Seq(1, 3, 6, 10)
Source code in pyochain/abc/_iterator.pyi
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
def scan[U](self, initial: U, func: Callable[[U, T], Option[U]]) -> PyoIterator[U]:
    """Transform elements by sharing state between iterations.

    `scan` takes two arguments:

        - an **initial** value which seeds the internal state
        - a **func** with two arguments

    The first being a reference to the internal state and the second an iterator element.

    The **func** can assign to the internal state to share state between iterations.

    On iteration, the **func** will be applied to each element of the iterator and the return value from the func, an Option, is returned by the next method.

    Thus the **func** can return `Some(value)` to yield value, or `NONE` to end the iteration.

    Args:
        initial (U): Initial state.
        func (Callable[[U, T], Option[U]]): Function that takes the current state and an item, and returns an Option.

    Returns:
        PyoIterator[U]: An iterable of the yielded values.

    Example:
        ```python
        from pyochain import Some, NONE, Range, Seq, Option

        def accumulate_until_limit(state: int, item: int) -> Option[int]:
            new_state = state + item
            match new_state:
                case _ if new_state <= 10:
                    return Some(new_state)
                case _:
                    return NONE

        out = Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
        assert out == Seq(1, 3, 6, 10)
        ```
    """

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:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the remaining elements.

Example
from pyochain import Seq

data = Seq(1, 2, 3)

assert data.iter().skip(1).collect(Seq) == Seq(2, 3)
assert data.iter().skip(5).collect(Seq).is_empty()
assert data.iter().skip(0).collect(Seq) == Seq(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
def skip(self, n: int) -> PyoIterator[T]:
    """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:
        PyoIterator[T]: An `Iterator` of the remaining elements.

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)

        assert data.iter().skip(1).collect(Seq) == Seq(2, 3)
        assert data.iter().skip(5).collect(Seq).is_empty()
        assert data.iter().skip(0).collect(Seq) == Seq(1, 2, 3)
        ```
    """

skip_while(predicate)

Skip elements from the Iterator while the predicate is True.

Afterwards, returns every element.

Note this does not produce any output until the predicate first becomes false, so this Iterator may have a lengthy start-up time.

Note

This is strictly equivalent to itertools::dropwhile(predicate, iterable).

Parameters:

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

Function to evaluate each item.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the items after skipping those for which the predicate is true.

Example
from pyochain import Seq

out = Seq(1, 2, 0, -1).iter().skip_while(lambda x: x > 0).collect(Seq)
assert out == Seq(0, -1)
Source code in pyochain/abc/_iterator.pyi
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
def skip_while(self, predicate: Callable[[T], object]) -> PyoIterator[T]:
    """Skip elements from the `Iterator` while the *predicate* is `True`.

    Afterwards, returns every element.

    Note this does not produce any output until the predicate first becomes false, so this `Iterator` may have a lengthy start-up time.

    Note:
        This is strictly equivalent to `itertools::dropwhile(predicate, iterable)`.

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

    Returns:
        PyoIterator[T]: An `Iterator` of the items after skipping those for which the predicate is true.

    Example:
        ```python
        from pyochain import Seq

        out = Seq(1, 2, 0, -1).iter().skip_while(lambda x: x > 0).collect(Seq)
        assert out == Seq(0, -1)
        ```
    """

slice(start=None, stop=None, step=None)

Make an Iterator that returns selected elements from the iterable.

Works like sequence slicing but does not support negative values for start, stop, or step.

Elements are returned consecutively unless step is set higher than one which results in items being skipped.

Parameters:

Name Type Description Default
start int | None

Starting index. If zero or None, iteration starts at zero. Otherwise, elements from the Iterator are skipped until start is reached

None
stop int | None

Ending index. If None, iteration continues until the input is exhausted, if at all. Otherwise, it stops at the specified position.

None
step int | None

Step size for the slice. Defaults to one.

None

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the sliced items.

Example
from pyochain import Seq, Range

txt = Seq("ABCDEFG")

assert txt.iter().slice(stop=2).join("") == "AB"
assert txt.iter().slice(2, 4).join("") == "CD"
assert txt.iter().slice(2, None).join("") == "CDEFG"
assert txt.iter().slice(0, None, 2).join("") == "ACEG"

data = Range(1, 6)

assert data.iter().slice(1, 4).collect(Seq) == (2, 3, 4)
assert data.iter().slice(step=2).collect(Seq) == (1, 3, 5)
assert data.iter().slice().collect(Seq) == (1, 2, 3, 4, 5)
Source code in pyochain/abc/_iterator.pyi
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
def slice(
    self,
    start: int | None = None,
    stop: int | None = None,
    step: int | None = None,
) -> PyoIterator[T]:
    """Make an `Iterator` that returns selected elements from the iterable.

    Works like sequence slicing but does not support negative values for *start*, *stop*, or *step*.

    Elements are returned consecutively unless *step* is set higher than one which results in items being skipped.

    Args:
        start (int | None): Starting index. If zero or `None`, iteration starts at zero. Otherwise, elements from the `Iterator` are skipped until start is reached
        stop (int | None): Ending index. If `None`, iteration continues until the input is exhausted, if at all. Otherwise, it stops at the specified position.
        step (int | None): Step size for the slice. Defaults to one.

    Returns:
        PyoIterator[T]: An `Iterator` of the sliced items.

    Example:
        ```python
        from pyochain import Seq, Range

        txt = Seq("ABCDEFG")

        assert txt.iter().slice(stop=2).join("") == "AB"
        assert txt.iter().slice(2, 4).join("") == "CD"
        assert txt.iter().slice(2, None).join("") == "CDEFG"
        assert txt.iter().slice(0, None, 2).join("") == "ACEG"

        data = Range(1, 6)

        assert data.iter().slice(1, 4).collect(Seq) == (2, 3, 4)
        assert data.iter().slice(step=2).collect(Seq) == (1, 3, 5)
        assert data.iter().slice().collect(Seq) == (1, 2, 3, 4, 5)
        ```
    """

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).

This is strictly equivalent to sorted(iterable, reverse=reverse).

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 Vec

assert Vec(3, 1, 2).iter().sort() == Vec(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
def sort[U: SupportsRichComparison](
    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).

    This is strictly equivalent to `sorted(iterable, reverse=reverse)`.

    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 Vec

        assert Vec(3, 1, 2).iter().sort() == Vec(1, 2, 3)
        ```
    """

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[[S], SupportsRichComparison]

Function to extract a comparison key from each element.

required
reverse bool

Whether to sort in descending order.

False

Returns:

Type Description
Vec[S]

Vec[S]: A Vec with elements sorted.

Example
from pyochain import Seq, Vec

str_numbers = Seq("3", "1", "2")
assert str_numbers.iter().sort_by(int) == Vec("1", "2", "3")
assert str_numbers.iter().sort_by(int, reverse=True) == Vec("3", "2", "1")
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

peoples = Seq(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
sorted_names = (
    peoples
    .iter()
    .sort_by(lambda x: x.age)
    .iter()
    .map(lambda x: x.name)
    .collect(Seq)
)
assert sorted_names == Seq("Bob", "Alice", "Charlie")
Source code in pyochain/abc/_iterator.pyi
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
def sort_by[S](
    self: PyoIterator[S],
    key: Callable[[S], SupportsRichComparison],
    *,
    reverse: bool = False,
) -> Vec[S]:
    """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[[S], SupportsRichComparison]): Function to extract a comparison key from each element.
        reverse (bool): Whether to sort in descending order.

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

    Example:
        ```python
        from pyochain import Seq, Vec

        str_numbers = Seq("3", "1", "2")
        assert str_numbers.iter().sort_by(int) == Vec("1", "2", "3")
        assert str_numbers.iter().sort_by(int, reverse=True) == Vec("3", "2", "1")
        from dataclasses import dataclass

        @dataclass
        class Person:
            name: str
            age: int

        peoples = Seq(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
        sorted_names = (
            peoples
            .iter()
            .sort_by(lambda x: x.age)
            .iter()
            .map(lambda x: x.name)
            .collect(Seq)
        )
        assert sorted_names == Seq("Bob", "Alice", "Charlie")
        ```
    """

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:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of every nth item.

Example
from pyochain import Seq

out = Seq(0, 1, 2, 3, 4, 5).iter().step_by(2).collect(Seq)
assert out == Seq(0, 2, 4)
Source code in pyochain/abc/_iterator.pyi
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
def step_by(self, step: int) -> PyoIterator[T]:
    """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:
        PyoIterator[T]: An `Iterator` of every nth item.

    Example:
        ```python
        from pyochain import Seq

        out = Seq(0, 1, 2, 3, 4, 5).iter().step_by(2).collect(Seq)
        assert out == Seq(0, 2, 4)
        ```
    """

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 Vec

data = Vec(1, 2, 3)

assert data.iter().sum() == 6
data.clear()
assert data.iter().sum() == 0
assert data.iter().sum(10) == 10
Source code in pyochain/abc/_iterator.pyi
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
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 Vec

        data = Vec(1, 2, 3)

        assert data.iter().sum() == 6
        data.clear()
        assert data.iter().sum() == 0
        assert data.iter().sum(10) == 10
        ```
    """

tail(n)

Return an Iterator of the last n elements of the Iterator.

Parameters:

Name Type Description Default
n int

Number of elements to return.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator containing the last n elements.

Example
from pyochain import Range

assert Range(10).iter().tail(2).collect(tuple) == (8, 9)
Source code in pyochain/abc/_iterator.pyi
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
def tail(self, n: int) -> PyoIterator[T]:
    """Return an `Iterator` of the last **n** elements of the `Iterator`.

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

    Returns:
        PyoIterator[T]: An `Iterator` containing the last **n** elements.

    Example:
        ```python
        from pyochain import Range

        assert Range(10).iter().tail(2).collect(tuple) == (8, 9)
        ```
    """

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:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the first n items.

Example
from pyochain import Seq

data = Seq(1, 2, 3)

assert data.iter().take(2).collect(Seq) == Seq(1, 2)
assert data.iter().take(5).collect(Seq) == Seq(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
def take(self, n: int) -> PyoIterator[T]:
    """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:
        PyoIterator[T]: An `Iterator` of the first n items.

    Example:
        ```python
        from pyochain import Seq

        data = Seq(1, 2, 3)

        assert data.iter().take(2).collect(Seq) == Seq(1, 2)
        assert data.iter().take(5).collect(Seq) == Seq(1, 2, 3)
        ```
    """

take_while(predicate)

Yield elements from the Iterator as long as the predicate evaluates to True.

Parameters:

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

Function to evaluate each item.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the items taken while the predicate is true.

Example
from pyochain import Seq

a = Seq(1, 2, 0).iter().take_while(lambda x: x > 0).collect(Seq)
assert a == (1, 2)

b = Seq(1, 4, 6, 3, 8).iter().take_while(lambda x: x < 5).collect(Seq)
assert b == (1, 4)
Source code in pyochain/abc/_iterator.pyi
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
def take_while(self, predicate: Callable[[T], object]) -> PyoIterator[T]:
    """Yield elements from the `Iterator` as long as the predicate evaluates to `True`.

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

    Returns:
        PyoIterator[T]: An `Iterator` of the items taken while the predicate is true.

    Example:
        ```python
        from pyochain import Seq

        a = Seq(1, 2, 0).iter().take_while(lambda x: x > 0).collect(Seq)
        assert a == (1, 2)

        b = Seq(1, 4, 6, 3, 8).iter().take_while(lambda x: x < 5).collect(Seq)
        assert b == (1, 4)
        ```
    """

tee(n=2)

Split Self into n new independants Iterators.

When the input iterable is already a tee iterator object, all members of the return tuple are constructed as if they had been produced by the upstream tee() call.

This “flattening step” allows nested tee() calls to share the same underlying data chain and to have a single update step rather than a chain of calls.

tee iterators are not threadsafe.

A RuntimeError may be raised when simultaneously using iterators returned by the same tee() call, even if the original Iterator is threadsafe.

This Iterator may require significant auxiliary storage (depending on how much temporary data needs to be stored).

In general, if one Iterator uses most or all of the data before another Iterator starts, it is faster to use collect() instead of tee().

Parameters:

Name Type Description Default
n int

The number of new Iterators to create. Defaults to 2.

2

Returns:

Type Description
tuple[PyoIterator[T], ...]

tuple[PyoIterator[T], ...]: A tuple of n new Iterators that can be used independently.

Example
from pyochain import Seq, Some

data = Seq(1, 2, 3)
it1, it2 = data.iter().tee()

assert it1.collect(Seq) == data
assert it2.collect(Seq) == data

The flattening property makes tee iterators efficiently peekable:

from pyochain import Iter
from pyochain.abc import PyoIterator

def lookahead[T](tee_iterator: PyoIterator[T]) -> Option[T]:
    '''Return the next value without moving the input forward'''
    [forked_iterator] = tee_iterator.tee(1)
    return forked_iterator.next()

iterator = Iter("abcdef")
# Make the input peekable
[iterator] = iterator.tee(1)
# Move the iterator forward
assert iterator.next() == Some("a")
# Check next value
assert lookahead(iterator) == Some("b")
# Continue moving forward
assert iterator.next() == Some("b")

Source code in pyochain/abc/_iterator.pyi
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
def tee(self, n: int = 2) -> tuple[PyoIterator[T], ...]:
    """Split `Self` into `n` new independants `Iterators`.

    When the input iterable is already a tee iterator object, all members of the return tuple are constructed as if they had been produced by the upstream tee() call.

    This “flattening step” allows nested tee() calls to share the same underlying data chain and to have a single update step rather than a chain of calls.

    tee iterators are not threadsafe.

    A `RuntimeError` may be raised when simultaneously using iterators returned by the same `tee()` call, even if the original `Iterator` is threadsafe.

    This `Iterator` may require significant auxiliary storage (depending on how much temporary data needs to be stored).

    In general, if one `Iterator` uses most or all of the data before another `Iterator` starts, it is faster to use `collect()` instead of `tee()`.

    Args:
        n (int): The number of new `Iterators` to create. Defaults to 2.

    Returns:
        tuple[PyoIterator[T], ...]: A tuple of `n` new `Iterators` that can be used independently.

    Example:
        ```python
        from pyochain import Seq, Some

        data = Seq(1, 2, 3)
        it1, it2 = data.iter().tee()

        assert it1.collect(Seq) == data
        assert it2.collect(Seq) == data
        ```

        The flattening property makes tee iterators efficiently peekable:
        ```python
        from pyochain import Iter
        from pyochain.abc import PyoIterator

        def lookahead[T](tee_iterator: PyoIterator[T]) -> Option[T]:
            '''Return the next value without moving the input forward'''
            [forked_iterator] = tee_iterator.tee(1)
            return forked_iterator.next()

        iterator = Iter("abcdef")
        # Make the input peekable
        [iterator] = iterator.tee(1)
        # Move the iterator forward
        assert iterator.next() == Some("a")
        # Check next value
        assert lookahead(iterator) == Some("b")
        # Continue moving forward
        assert iterator.next() == Some("b")
        ```
    """

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 Iterator 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 Range, Some, Ok, Err, NONE, Vec, Option, Seq, Iter

# Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
assert Range(1, 4).iter().map(Some).try_collect().unwrap() == Vec(1, 2, 3)
# Failing to collect in the same way:
assert Seq(Some(1), Some(2), NONE, Some(3)).iter().try_collect().is_none()

# A similar example, but with Result:
Range(1, 4).iter().map(Ok).try_collect().unwrap() == Vec(1, 2, 3)
assert Seq(Ok(1), Err("error"), Ok(3)).iter().try_collect().is_none()

def external_fn(x: int) -> Option[int]:
    if x % 2 == 0:
        return Some(x)
    return NONE

assert Range(1, 5).iter().map(external_fn).try_collect().is_none()
# Demonstrating that the iterator remains usable after a failure:
it = Iter(Some(1), NONE, Some(3), Some(4))
assert it.try_collect().is_none()
assert it.try_collect().unwrap() == Vec(3, 4)
Source code in pyochain/abc/_iterator.pyi
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
def try_collect[U](
    self: PyoIterator[Option[U]] | PyoIterator[Result[U, Any]],
) -> 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 `Iterator` 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 Range, Some, Ok, Err, NONE, Vec, Option, Seq, Iter

        # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
        assert Range(1, 4).iter().map(Some).try_collect().unwrap() == Vec(1, 2, 3)
        # Failing to collect in the same way:
        assert Seq(Some(1), Some(2), NONE, Some(3)).iter().try_collect().is_none()

        # A similar example, but with Result:
        Range(1, 4).iter().map(Ok).try_collect().unwrap() == Vec(1, 2, 3)
        assert Seq(Ok(1), Err("error"), Ok(3)).iter().try_collect().is_none()

        def external_fn(x: int) -> Option[int]:
            if x % 2 == 0:
                return Some(x)
            return NONE

        assert Range(1, 5).iter().map(external_fn).try_collect().is_none()
        # Demonstrating that the iterator remains usable after a failure:
        it = Iter(Some(1), NONE, Some(3), Some(4))
        assert it.try_collect().is_none()
        assert it.try_collect().unwrap() == Vec(3, 4)
        ```
    """

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, Some

def is_even(x: int) -> Result[bool, str]:
    return Ok(x % 2 == 0) if x >= 0 else Err("negative number")

assert Range(1, 6).iter().try_find(is_even).unwrap().unwrap() == 2
Source code in pyochain/abc/_iterator.pyi
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
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, Some

        def is_even(x: int) -> Result[bool, str]:
            return Ok(x % 2 == 0) if x >= 0 else Err("negative number")

        assert Range(1, 6).iter().try_find(is_even).unwrap().unwrap() == 2
        ```
    """

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 Ok, Err, Result, Range, Iter, Seq

def checked_add(acc: int, x: int) -> Result[int, str]:
    new_val = acc + x
    if new_val > 100:
        return Err("overflow")
    else:
        return Ok(new_val)

assert Range(1, 4).iter().try_fold(0, checked_add).unwrap() == 6
error = Iter.from_count(50, -10).take(5).try_fold(0, checked_add)
assert error.unwrap_err() == "overflow"
assert Seq().iter().try_fold(0, checked_add).unwrap() == 0
Source code in pyochain/abc/_iterator.pyi
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
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 Ok, Err, Result, Range, Iter, Seq

        def checked_add(acc: int, x: int) -> Result[int, str]:
            new_val = acc + x
            if new_val > 100:
                return Err("overflow")
            else:
                return Ok(new_val)

        assert Range(1, 4).iter().try_fold(0, checked_add).unwrap() == 6
        error = Iter.from_count(50, -10).take(5).try_fold(0, checked_add)
        assert error.unwrap_err() == "overflow"
        assert Seq().iter().try_fold(0, checked_add).unwrap() == 0
        ```
    """

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")

assert Iter(1, 2, 3, 4, 5).try_for_each(validate_positive).is_ok()

# Short-circuit on first error:
error = Iter(1, 2, -1, 4).try_for_each(validate_positive).unwrap_err()
assert error == "Value -1 is not positive"
Source code in pyochain/abc/_iterator.pyi
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
def try_for_each[E](self, f: Callable[[T], Result[Any, E]]) -> Result[tuple[()], E]:
    """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")

        assert Iter(1, 2, 3, 4, 5).try_for_each(validate_positive).is_ok()

        # Short-circuit on first error:
        error = Iter(1, 2, -1, 4).try_for_each(validate_positive).unwrap_err()
        assert error == "Value -1 is not positive"
        ```
    """

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[[S, S], Result[S, E]]

Function that reduces two items, returns a Result[S, E].

required

Returns:

Type Description
Result[Option[S], E]

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

Example
from pyochain import Ok, Err, Result, Range, Seq

def checked_add(x: int, y: int) -> Result[int, str]:
    if x + y > 100:
        return Err("overflow")
    else:
        return Ok(x + y)

assert Range(1, 4).iter().try_reduce(checked_add).is_ok()
assert Seq(50, 60).iter().try_reduce(checked_add).is_err()
assert Range(0).iter().try_reduce(checked_add).unwrap().is_none()
Source code in pyochain/abc/_iterator.pyi
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
def try_reduce[S, E](
    self: PyoIterator[S], func: Callable[[S, S], Result[S, E]]
) -> Result[Option[S], 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[[S, S], Result[S, E]]): Function that reduces two items, returns a `Result[S, E]`.

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

    Example:
        ```python
        from pyochain import Ok, Err, Result, Range, Seq

        def checked_add(x: int, y: int) -> Result[int, str]:
            if x + y > 100:
                return Err("overflow")
            else:
                return Ok(x + y)

        assert Range(1, 4).iter().try_reduce(checked_add).is_ok()
        assert Seq(50, 60).iter().try_reduce(checked_add).is_err()
        assert Range(0).iter().try_reduce(checked_add).unwrap().is_none()
        ```
    """

unique()

Return only unique elements of the Iterator.

This has the same effect as collecting the Iterator into a StableSet (keeps original ordering), but this returns a new Iterator.

This means that this operation stay lazy, and can be more efficient depending on the situation.

If you just need unique elements in a collection right away, collecting the Iterator into a set-like collection may have more raw speed.

Thus

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the unique items.

Example
from pyochain import Vec, Set, Seq

data = Seq(1, 1, 2, 2, 3, 3)

assert data.iter().unique().collect(Seq) == Seq(1, 2, 3)
assert data.pipe(Set).iter().sort() == Vec(1, 2, 3)
Source code in pyochain/abc/_iterator.pyi
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
def unique(self) -> PyoIterator[T]:
    """Return only unique elements of the `Iterator`.

    This has the same effect as collecting the `Iterator` into a `StableSet` (keeps original ordering), but this returns a new `Iterator`.

    This means that this operation stay lazy, and can be more efficient depending on the situation.

    If you just need unique elements in a collection right away, collecting the `Iterator` into a `set`-like collection may have more raw speed.

    Thus

    Returns:
        PyoIterator[T]: An `Iterator` of the unique items.

    Example:
        ```python
        from pyochain import Vec, Set, Seq

        data = Seq(1, 1, 2, 2, 3, 3)

        assert data.iter().unique().collect(Seq) == Seq(1, 2, 3)
        assert data.pipe(Set).iter().sort() == Vec(1, 2, 3)
        ```
    """

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:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the unique items.

Example
from pyochain import Seq

data = Seq("cat", "mouse", "dog", "hen")
assert data.iter().unique_by(key=len).collect(Seq) == Seq("cat", "mouse")
Source code in pyochain/abc/_iterator.pyi
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
def unique_by(self, key: Callable[[T], Any]) -> PyoIterator[T]:
    """Return only unique elements of the iterable.

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

    Returns:
        PyoIterator[T]: An `Iterator` of the unique items.

    Example:
        ```python
        from pyochain import Seq

        data = Seq("cat", "mouse", "dog", "hen")
        assert data.iter().unique_by(key=len).collect(Seq) == Seq("cat", "mouse")
        ```
    """

unpack_into(func, *args, **kwargs)

Unpack the Iterator in the provided func, and return the result.

This is similar to Pipe::pipe, but instead of passing PyoIterator[T], we pass the elements inside PyoIterator[T].

This avoids you to do iterator.pipe(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))

assert 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.
assert data.iter().unpack_into(lambda a, b, c: a + b + c) == 6
Source code in pyochain/abc/_iterator.pyi
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
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 `Pipe::pipe`, but instead of passing `PyoIterator[T]`, we pass the elements inside `PyoIterator[T]`.

    This avoids you to do `iterator.pipe(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))

        assert 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.
        assert data.iter().unpack_into(lambda a, b, c: a + b + c) == 6
        ```
    """

unzip()

Converts an Iterator of pairs into a pair of Iterators.

This function is, in some sense, the opposite of zip.

Both Iterators share the same underlying source.

Values consumed by one Iterator remain in the shared buffer until the other Iterator consumes them too.

Returns:

Type Description
tuple[PyoIterator[U], PyoIterator[V]]

tuple[PyoIterator[U], PyoIterator[V]]: A tuple containing two Iterators, one for each element of the pairs.

Example
from pyochain import Seq

data = Seq("a", "b", "c")
left, right = data.iter().enumerate().unzip()

assert left.collect(Seq) == Seq(0, 1, 2)
assert right.collect(Seq) == Seq("a", "b", "c")
Source code in pyochain/abc/_iterator.pyi
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
def unzip[U, V](
    self: PyoIterator[tuple[U, V]],
) -> tuple[PyoIterator[U], PyoIterator[V]]:
    """Converts an `Iterator` of pairs into a pair of `Iterator`s.

    This function is, in some sense, the opposite of [`zip`][].

    Both `Iterator`s share the same underlying source.

    Values consumed by one `Iterator` remain in the shared buffer until the other `Iterator` consumes them too.

    Returns:
        tuple[PyoIterator[U], PyoIterator[V]]: A tuple containing two `Iterator`s, one for each element of the pairs.

    Example:
        ```python
        from pyochain import Seq

        data = Seq("a", "b", "c")
        left, right = data.iter().enumerate().unzip()

        assert left.collect(Seq) == Seq(0, 1, 2)
        assert right.collect(Seq) == Seq("a", "b", "c")
        ```
    """

with_position()

Return an Iterator over (Position, T) tuples.

The Position indicates whether the item T is the first, middle, last, or only element in the Iterator.

Returns:

Type Description
PyoIterator[tuple[Position, T]]

PyoIterator[tuple[Position, T]]: An Iterator of (Position, item) tuples.

Example
from pyochain import Seq

data = Seq("a", "b", "c", "d", "e")
a = data.iter().with_position().collect(Seq)
assert a == Seq(
    ("first", "a"),
    ("middle", "b"),
    ("middle", "c"),
    ("middle", "d"),
    ("last", "e"),
)

b = data.iter().take(1).with_position().collect(Seq)
assert b == Seq([("only", "a")])

c = data.iter().take(2).with_position().collect(Seq)
assert c == Seq(("first", "a"), ("last", "b"))
Source code in pyochain/abc/_iterator.pyi
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
def with_position(self) -> PyoIterator[tuple[Position, T]]:
    """Return an `Iterator` over (`Position`, `T`) tuples.

    The `Position` indicates whether the item `T` is the first, middle, last, or only element in the `Iterator`.

    Returns:
        PyoIterator[tuple[Position, T]]: An `Iterator` of (`Position`, item) tuples.

    Example:
        ```python
        from pyochain import Seq

        data = Seq("a", "b", "c", "d", "e")
        a = data.iter().with_position().collect(Seq)
        assert a == Seq(
            ("first", "a"),
            ("middle", "b"),
            ("middle", "c"),
            ("middle", "d"),
            ("last", "e"),
        )

        b = data.iter().take(1).with_position().collect(Seq)
        assert b == Seq([("only", "a")])

        c = data.iter().take(2).with_position().collect(Seq)
        assert c == Seq(("first", "a"), ("last", "b"))
        ```
    """

zip(*others, strict=False)

zip(*, strict: bool = False) -> PyoIterator[tuple[T]]
zip(
    iter2: Iterable[T2], /, *, strict: bool = False
) -> PyoIterator[tuple[T, T2]]
zip(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    /,
    *,
    strict: bool = False,
) -> PyoIterator[tuple[T, T2, T3]]
zip(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    /,
    *,
    strict: bool = False,
) -> PyoIterator[tuple[T, T2, T3, T4]]
zip(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    /,
    *,
    strict: bool = False,
) -> PyoIterator[tuple[T, T2, T3, T4, T5]]
zip(
    *others: Iterable[S], strict: bool = False
) -> PyoIterator[tuple[S, ...]]

Yields n-length tuples, where n is the number of iterables passed as positional arguments.

The i-th element in every tuple comes from the i-th iterable argument to .zip().

This continues until the shortest argument is exhausted.

Note

map_star can then be used for subsequent operations on the index and value, in a destructuring manner. This keep the code clean and readable, without index access like [0] and [1] for inline lambdas.

Parameters:

Name Type Description Default
*others Iterable[Any]

Other iterables to zip with.

()
strict bool

If True and one of the arguments is exhausted before the others, raise a ValueError.

False

Returns:

Type Description
PyoIterator[tuple[Any, ...]]

PyoIterator[tuple[Any, ...]]: An Iterator of tuples containing elements from the zipped PyoIterator and other iterables.

Example
from pyochain import Seq

a = Seq(1, 2).iter().zip((10, 20)).collect(Seq)
assert a == Seq((1, 10), (2, 20))

b = Seq("a", "b").iter().zip((1, 2, 3)).collect(Seq)
assert b == Seq(("a", 1), ("b", 2))
Source code in pyochain/abc/_iterator.pyi
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
def zip(
    self, /, *others: Iterable[Any], strict: bool = False
) -> PyoIterator[tuple[Any, ...]]:
    """Yields n-length tuples, where n is the number of iterables passed as positional arguments.

    The i-th element in every tuple comes from the i-th iterable argument to `.zip()`.

    This continues until the shortest argument is exhausted.

    Note:
        [`map_star`][] can then be used for subsequent operations on the index and value, in a destructuring manner.
        This keep the code clean and readable, without index access like `[0]` and `[1]` for inline lambdas.

    Args:
        *others (Iterable[Any]): Other iterables to zip with.
        strict (bool): If `True` and one of the arguments is exhausted before the others, raise a ValueError.

    Returns:
        PyoIterator[tuple[Any, ...]]: An `Iterator` of tuples containing elements from the zipped `PyoIterator` and other iterables.

    Example:
        ```python
        from pyochain import Seq

        a = Seq(1, 2).iter().zip((10, 20)).collect(Seq)
        assert a == Seq((1, 10), (2, 20))

        b = Seq("a", "b").iter().zip((1, 2, 3)).collect(Seq)
        assert b == Seq(("a", 1), ("b", 2))
        ```
    """

zip_longest(*others)

zip_longest(
    iter2: Iterable[T2],
) -> PyoIterator[tuple[Option[T], Option[T2]]]
zip_longest(
    iter2: Iterable[T2], iter3: Iterable[T3]
) -> PyoIterator[tuple[Option[T], Option[T2], Option[T3]]]
zip_longest(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
) -> PyoIterator[
    tuple[Option[T], Option[T2], Option[T3], Option[T4]]
]
zip_longest(
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
) -> PyoIterator[
    tuple[
        Option[T],
        Option[T2],
        Option[T3],
        Option[T4],
        Option[T5],
    ]
]

Make an Iterator that aggregates elements from each of Self and input Iterables.

If the iterables are of uneven length, missing values are filled-in with Null.

Otherwise, wrap elements in Some when they are present.

Iteration continues until the longest iterable is exhausted.

If one of the iterables is potentially infinite, then the resulting Iterator should be followed with a method that limits the number of calls.

For example, slice or take_while.

Parameters:

Name Type Description Default
*others Iterable[Any]

Other iterables to zip with.

()

Returns:

Type Description
ZippedLongest[T]

ZippedLongest[T]: An Iterator of tuples containing optional elements from the zipped iterables.

Example
from pyochain import Iter, Some, NONE, Vec, Seq

out = Seq(1, 2).iter().zip_longest([10]).collect(Vec)
assert out == [(Some(1), Some(10)), (Some(2), NONE)]

# Can be combined with try collect to filter out the NONE:
zipped = out.iter().map(lambda x: Iter(x).try_collect()).collect(Vec)
assert zipped == [Some(Vec(1, 10)), NONE]
Source code in pyochain/abc/_iterator.pyi
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
def zip_longest(self, *others: Iterable[Any]) -> ZippedLongest[T]:
    """Make an `Iterator` that aggregates elements from each of `Self` and input `Iterable`s.

    If the iterables are of uneven length, missing values are filled-in with `Null`.

    Otherwise, wrap elements in `Some` when they are present.

    Iteration continues until the longest iterable is exhausted.

    If one of the iterables is potentially infinite, then the resulting `Iterator` should be followed with a method that limits the number of calls.

    For example, [`slice`][] or [`take_while`][].

    Args:
        *others (Iterable[Any]): Other iterables to zip with.

    Returns:
        ZippedLongest[T]: An `Iterator` of tuples containing optional elements from the zipped iterables.

    Example:
        ```python
        from pyochain import Iter, Some, NONE, Vec, Seq

        out = Seq(1, 2).iter().zip_longest([10]).collect(Vec)
        assert out == [(Some(1), Some(10)), (Some(2), NONE)]

        # Can be combined with try collect to filter out the NONE:
        zipped = out.iter().map(lambda x: Iter(x).try_collect()).collect(Vec)
        assert zipped == [Some(Vec(1, 10)), NONE]
        ```
    """