Skip to content

PyoIterator

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


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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

All concrete subclasses must implement the required Iterator dunder methods:

  • __iter__
  • __next__
Example
>>> from pyochain import Seq
>>> from pyochain.abc import PyoIterator
>>>
>>> class Count(PyoIterator[int]):
...     def __init__(self, start: int = 0):
...         self.current = start
...
...     def __iter__(self):
...         return self
...
...     def __next__(self):
...         val = self.current
...         self.current += 1
...         return val
>>>
>>> counter = Count(5)
>>> counter.next()
Some(5)
>>> counter.next()
Some(6)
>>> counter.iter().take(3).collect(Seq)
Seq(7, 8, 9)
Source code in src/pyochain/abc/_iterator.py
  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
class PyoIterator[T](PyoIterable[T], Iterator[T], ABC):
    """Extends `PyoIterable[T]` and `collections.abc.Iterator[T]`.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    - `__iter__`
    - `__next__`

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

        ```
    """

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

    @no_doctest
    @classmethod
    def _from_iterable[I](cls, iterable: Iterable[I]) -> PyoIterator[I]:
        """Internal constructor.

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

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

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

        Returns:
            PyoIterator[I]: A new instance of the concrete `PyoIterator` subclass.

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

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

        """
        return cls(iterable)  # pyright: ignore[reportReturnType, reportCallIssue]

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

        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 equivalent of `.insert()` but as a 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
            >>> Iter.once(42).collect(Seq)
            Seq(42,)

            ```
        """
        return cls._from_iterable((value,))

    @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 equivalent of [`PyoIterator::insert`][PyoIterator.insert] but as a constructor.

        Unlike `PyoIterator::once`, this function will lazily generate the value on request.

        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
            >>> Iter.once_with(lambda: 42).collect(Seq)
            Seq(42,)

            ```
        """

        def _once_with() -> Generator[R]:
            yield func(*args, **kwargs)

        return cls._from_iterable(_once_with())

    @classmethod
    def from_count(cls, start: int = 0, step: int = 1) -> PyoIterator[int]:
        """Create an `Iterator` of evenly spaced values.

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

            Be sure to use `PyoIterator::take` or `PyoIterator::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 sequence.
            step (int): Difference between consecutive values.

        Returns:
            PyoIterator[int]: An `Iterator` generating the sequence.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter.from_count(10, 2).take(3).collect(Seq)
            Seq(10, 12, 14)

            ```
        """
        return cls._from_iterable(itertools.count(start, step))

    @classmethod
    def from_fn[**P, R](
        cls, f: Callable[P, Option[R]], *args: P.args, **kwargs: P.kwargs
    ) -> PyoIterator[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, Seq
            >>>
            >>> 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
            >>>
            >>> Iter.from_fn(make_counter(5)).collect(Seq)
            Seq(1, 2, 3, 4, 5)

            ```
            Stateful callable class:
            ```python
            >>> from pyochain import Iter, Some, NONE
            >>> from dataclasses import dataclass
            >>> @dataclass
            ... class Counter:
            ...     max: int
            ...     count: int = 0
            ...
            ...     def __call__(self) -> Option[int]:
            ...         self.count += 1
            ...         return Some(self.count) if self.count <= self.max else NONE
            >>>
            >>> Iter.from_fn(Counter(5)).collect(Seq)
            Seq(1, 2, 3, 4, 5)

            ```
            Simulated file/queue reader:
            ```python
            >>> from pyochain import Iter, Some, NONE
            >>> from pyochain.collections import Deque
            >>>
            >>> def queue_consumer(items: Deque[int]) -> Callable[[], Option[int]]:
            ...     def consume() -> Option[int]:
            ...         return Some(items.pop_left()) if items else NONE
            ...
            ...     return consume
            >>>
            >>> Iter.from_fn(Deque([1, 2, 3]).pipe(queue_consumer)).collect(Seq)
            Seq(1, 2, 3)

            ```
        """
        return cls._from_iterable(tls.FromFn(f, *args, **kwargs))

    @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
            >>>
            >>> Iter.successors(Some(1), next_pow10).collect(Seq)
            Seq(1, 10, 100, 1000, 10000)
            >>> Iter.successors(NONE, next_pow10).collect(Seq)
            Seq()

            ```
        """
        return cls._from_iterable(tls.Successors(first, succ))

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

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

        Be sure to use [`PyoIterator::take`][PyoIterator.take] or [`PyoIterator::slice`][PyoIterator.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:
            [`PyoIterator::cycle`][cycle] to repeat the **elements** of the `Iterator`.
            [`PyoIterator::repeat`][repeat] to repeat the **entire** `Iterator`.

        Example:
            ```python
            >>> from pyochain import Seq, Iter
            >>> Iter.from_repeat(1, 3).collect(Seq)
            Seq(1, 1, 1)
            >>> Iter.from_repeat(("a", "b"), 2).collect(Seq)
            Seq(('a', 'b'), ('a', 'b'))

            ```
            Shared reference behavior:
            ```python
            >>> from pyochain import Vec
            >>>
            >>> base = ["Alice", "Bob", "Charlie"]
            >>>
            >>> first, second = Iter.from_repeat(base).take(2).collect(tuple)
            >>> first.append("Joe")
            >>> first
            ['Alice', 'Bob', 'Charlie', 'Joe']
            >>> base
            ['Alice', 'Bob', 'Charlie', 'Joe']
            >>> second
            ['Alice', 'Bob', 'Charlie', 'Joe']
            >>> first is second and first is base and second is base
            True

            ```
        """
        if n is None:
            return cls._from_iterable(itertools.repeat(obj))
        return cls._from_iterable(itertools.repeat(obj, n))

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

        Returns:
            int: The count of elements.

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

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

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

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

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

        If any of them return false, it returns false.

        An empty `Iterator` returns true.

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

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

        Example:
            ```python
            >>> from pyochain import Iter
            >>> Iter((1, True)).all()
            True
            >>> Iter(()).all()
            True
            >>> Iter((1, 0)).all()
            False
            >>> def is_even(x: int) -> bool:
            ...     return x % 2 == 0
            >>>
            >>> Iter((2, 4, 6)).all(is_even)
            True
            >>> Iter(("a", "", "c")).all()
            False
            >>> Iter((1, None, 3)).all()
            False

            ```
        """
        if predicate is None:
            return all(iter(self))
        return tls.all(iter(self), predicate)

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

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

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

        If they all return false, it returns false.

        An empty `Iterator` returns false.

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

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

        Example:
            ```python
            >>> from pyochain import Iter, Range
            >>> Iter((0, 1)).any()
            True
            >>> Range(0, 0).iter().any()
            False
            >>> def is_even(x: int) -> bool:
            ...     return x % 2 == 0
            >>> Iter((1, 3, 4)).any(is_even)
            True

            ```
        """
        if predicate is None:
            return any(iter(self))
        return tls.any(iter(self), predicate)

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

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

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

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

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

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

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

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

        Comparison is performed element by element.

        Two `Iterable`s are equal only if:

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

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

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

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

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

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

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

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

        The result becomes `True` as soon as:

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

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

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

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

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

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

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

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

        The first differing pair decides the result.

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

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

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

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

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

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

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

        The first differing pair of elements decides the result.

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

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

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

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

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

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

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

        The first differing pair of elements decides the result.

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

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

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

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

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

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

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

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

        The first differing pair decides the result.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Returns:
            T: Single value resulting from cumulative reduction.

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

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

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

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

        Returns:
            B: The final accumulated value.

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

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

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

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

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

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

        Returns:
            B: The final accumulated value.

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

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

            ```
        """

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

        return functools.reduce(_reducer, iter(self), init)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            >>> from pyochain import Seq
            >>> data = Seq((1, 2, 2))
            >>> data.iter().is_sorted()
            True
            >>> data.iter().is_sorted(strict=True)
            False

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

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

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

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

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

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

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

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

            ```
            If strict, tests for strict sorting, that is, returns False if equal elements are found:
            ```python
            >>> from pyochain import Seq
            >>> data = Seq(("1", "2", "2"))
            >>> data.iter().is_sorted_by(int)
            True
            >>> data.iter().is_sorted_by(int, strict=True)
            False

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

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

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

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

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

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

        Example:
            ```python
            >>> from pyochain import Iter, Range
            >>> Iter("AaaA").all_equal(key=str.casefold)
            True
            >>> Range(0, 9).iter().all_equal(key=lambda x: x < 10)
            True

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

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

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

        Elements are assumed to be hashable.

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

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

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

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

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

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

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

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

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

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

        Credits to more-itertools for the implementation.

        Returns:
            int: The index of the maximum value.

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

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

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

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

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

        Credits to more-itertools for the implementation.

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

        Returns:
            int: The index of the maximum value.

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

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

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

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

        Credits to more-itertools for the implementation.

        Returns:
            int: The index of the minimum value.

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

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

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

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

        Credits to more-itertools for the implementation.

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

        Returns:
            int: The index of the minimum value.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        This is equivalent to `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(0, 5)
            >>> data.iter().collect(list)
            [0, 1, 2, 3, 4]
            >>> data.iter().collect(Vec)
            Vec(0, 1, 2, 3, 4)
            >>> data.iter().map(str).enumerate().collect(Dict)
            Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Example:
            ```python
            >>> from pyochain import Seq
            >>> str_numbers = Seq(("3", "1", "2"))
            >>> str_numbers.iter().sort_by(int)
            Vec('1', '2', '3')
            >>> 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)
            ... )
            >>> sorted_names
            Seq('Bob', 'Alice', 'Charlie')

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

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

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

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

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

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

            ```
        """
        from collections import deque

        from ..collections import Deque

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

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

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

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

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

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

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

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

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

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

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

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

        Returns:
            str: The joined string.

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

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

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

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

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

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

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

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

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

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

        For comparing elements using a custom **key** function, use [`min_by`][min_by] instead.

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

        Returns:
            U: The minimum value.

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

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

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

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

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

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

        Example:
            ```python
            >>> from pyochain import Seq
            >>> from dataclasses import dataclass
            >>>
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            ...     is_student: bool
            ...
            ...     def get_discount(self) -> float:
            ...         return 0.1 if self.is_student else 0.0
            >>>
            >>> alice = Person("Alice", 30, False)
            >>> bob = Person("Bob", 22, True)
            >>> charlie = Person("Charlie", 25, False)
            >>> persons = Seq((alice, bob, charlie))
            >>>
            >>> persons.iter().min_by(lambda p: p.age).name
            'Bob'
            >>> persons.iter().min_by(lambda p: p.name).name
            'Alice'
            >>> persons.iter().min_by(Person.get_discount).name
            'Alice'

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

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

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

        For comparing elements using a custom **key** function, use [`max_by`][max_by] instead.

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

        Returns:
            U: The maximum value.

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

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

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

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

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

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

        Example:
            ```python
            >>> from pyochain import Seq
            >>> from dataclasses import dataclass
            >>>
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            ...     is_student: bool
            ...
            ...     def get_discount(self) -> float:
            ...         return 0.1 if self.is_student else 0.0
            >>>
            >>> alice = Person("Alice", 30, False)
            >>> bob = Person("Bob", 22, True)
            >>> charlie = Person("Charlie", 25, False)
            >>> persons = Seq((alice, bob, charlie))
            >>>
            >>> persons.iter().max_by(lambda p: p.age).name
            'Alice'
            >>> persons.iter().max_by(lambda p: p.name).name
            'Charlie'
            >>> persons.iter().max_by(Person.get_discount).name
            'Bob'

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

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

        This is similar to `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))
            >>> data.iter().unpack_into(foo, x="Result: ")
            'Result: 6'
            >>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
            >>> data.iter().unpack_into(lambda a, b, c: a + b + c)
            6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Args:
            predicate (Callable[[T], bool]): 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)
            >>> out
            Seq(0, -1)

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

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

        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
            >>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect(Seq)
            Seq('A', 'C', 'E', 'F')

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

    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 Seq, Set
            >>> data = Seq((1, 1, 2, 2, 3, 3))
            >>> data.iter().unique().collect(Seq)
            Seq(1, 2, 3)
            >>> data.pipe(Set).iter().sort()
            Vec(1, 2, 3)

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

    def unique_by(self, key: Callable[[T], Any]) -> PyoIterator[T]:  # pyright: ignore[reportExplicitAny]
        """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"))
            >>> data.iter().unique_by(key=len).collect(Seq)
            Seq('cat', 'mouse')

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

    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))
            >>> data.iter().take(2).collect(Seq)
            Seq(1, 2)
            >>> data.iter().take(5).collect(Seq)
            Seq(1, 2, 3)

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

    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))
            >>> data.iter().skip(1).collect(Seq)
            Seq(2, 3)
            >>> data.iter().skip(5).collect(Seq)
            Seq()
            >>> data.iter().skip(0).collect(Seq)
            Seq(1, 2, 3)

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

    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
            >>> Seq((0, 1, 2, 3, 4, 5)).iter().step_by(2).collect(Seq)
            Seq(0, 2, 4)

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

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

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

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

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

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

    def cycle(self) -> PyoIterator[T]:
        """Repeat the `Iterator` indefinitely.

        Warning:
            This creates an infinite `Iterator`.

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

        See Also:
            [`PyoIterator::repeat`][repeat] to repeat *self* as elements (`PyoIterator[PyoIterator[T]]`).

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

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

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

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

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

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

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

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

        Returns:
            PyoIterator[T]: A new Iterable wrapper with the value prepended.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        In principle, `PyoIterator::accumulate` is similar to `PyoIterator::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 `PyoIterator::accumulate` is what would have been returned by `PyoIterator::fold` if it had been used instead.

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

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

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

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

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

        The returned tuple contains two elements:

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

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

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

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

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

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

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

    def array_chunks(self, size: int) -> PyoIterator[PyoIterator[T]]:
        """Yield subiterators (chunks) that each yield a fixed number elements, determined by size.

        The last chunk will be shorter if there are not enough elements.

        Args:
            size (int): Number of elements in each chunk.

        Returns:
            PyoIterator[PyoIterator[T]]: An iterable of iterators, each yielding n elements.

        If the sub-iterables are read in order, the elements of *iterable*
        won't be stored in memory.

        If they are read out of order, :func:`itertools.tee` is used to cache
        elements as necessary.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> all_chunks = Iter.from_count().array_chunks(4)
            >>> c_1, c_2, c_3 = all_chunks.next(), all_chunks.next(), all_chunks.next()
            >>> # c_1's elements have been cached; c_3's haven't been
            >>> c_2.unwrap().collect(Seq)
            Seq(4, 5, 6, 7)
            >>> c_1.unwrap().collect(Seq)
            Seq(0, 1, 2, 3)
            >>> c_3.unwrap().collect(Seq)
            Seq(8, 9, 10, 11)

            ```
            You can collect the chunks into a collection of collections, for example:
            ```python
            >>> from pyochain import Seq
            >>> from pyochain.abc import PyoIterable
            >>> def collect_all_chunks(data: PyoIterable[int]) -> Seq[Seq[int]]:
            ...     return (
            ...         data
            ...         .iter()
            ...         .array_chunks(3)
            ...         .map(lambda c: c.collect(Seq))
            ...         .collect(Seq)
            ...     )
            >>> Seq((1, 2, 3, 4, 5, 6)).pipe(collect_all_chunks)
            Seq(Seq(1, 2, 3), Seq(4, 5, 6))
            >>> Seq((1, 2, 3, 4, 5, 6, 7, 8)).pipe(collect_all_chunks)
            Seq(Seq(1, 2, 3), Seq(4, 5, 6), Seq(7, 8))

            ```
        """
        from collections import deque
        from contextlib import suppress

        def _chunks() -> Iterator[PyoIterator[T]]:
            def _ichunk(
                iterator: Iterator[T], n: int
            ) -> tuple[Iterator[T], Callable[[int], int]]:
                cache: deque[T] = deque()
                chunk = itertools.islice(iterator, n)

                def _generator() -> Iterator[T]:
                    with suppress(StopIteration):
                        while True:
                            if cache:
                                yield cache.popleft()
                            else:
                                yield next(chunk)

                def _materialize_next(n: int) -> int:
                    to_cache = n - len(cache)

                    # materialize up to n
                    if to_cache > 0:
                        cache.extend(itertools.islice(chunk, to_cache))

                    # return number materialized up to n
                    return min(n, len(cache))

                return (_generator(), _materialize_next)

            new = self._from_iterable
            while True:
                # Create new chunk
                chunk, materialize_next = _ichunk(iter(self), size)

                # Check to see whether we're at the end of the source iterable
                if not materialize_next(size):
                    return

                yield new(chunk)
                _ = materialize_next(size)

        return self._from_iterable(_chunks())

    @overload
    def flatten[U](self: PyoIterator[KeysView[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Iterable[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Generator[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[ValuesView[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Iterator[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Collection[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Sequence[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[list[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[tuple[U, ...]]) -> PyoIterator[U]: ...

    @overload
    def flatten[U](self: PyoIterator[PyoIterator[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Iter[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Seq[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Set[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[SetMut[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten[U](self: PyoIterator[Vec[U]]) -> PyoIterator[U]: ...
    @overload
    def flatten(self: PyoIterator[range]) -> PyoIterator[int]: ...
    @overload
    def flatten(self: PyoIterator[Range]) -> PyoIterator[int]: ...
    @overload
    def flatten[U](self: PyoIterator[Dict[U, Any]]) -> PyoIterator[U]: ...  # pyright: ignore[reportExplicitAny]
    def flatten[U: AnyIter](self: PyoIterator[U]) -> PyoIterator[Any]:  # pyright: ignore[reportExplicitAny]
        """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[Any]: An `Iterator` of flattened elements.


        Example:
            Basic usage:
            ```python
            >>> from pyochain import Iter, Seq
            >>> data = ((1, 2, 3, 4), (5, 6))
            >>> flattened = Iter(data).flatten().collect(Seq)
            >>> flattened
            Seq(1, 2, 3, 4, 5, 6)

            ```
            Mapping and then flattening:
            ```python
            >>> from pyochain import Iter
            >>> words = Iter(("alpha", "beta", "gamma"))
            >>> merged = words.flatten().collect(Seq)
            >>> merged
            Seq('a', 'l', 'p', 'h', 'a', 'b', 'e', 't', 'a', 'g', 'a', 'm', 'm', 'a')

            ```
            Flattening only removes one level of nesting at a time:
            ```python
            >>> from pyochain import Iter
            >>> d3 = (((1, 2), (3, 4)), ((5, 6), (7, 8)))
            >>> d2 = Iter(d3).flatten().collect(Seq)
            >>> d2
            Seq((1, 2), (3, 4), (5, 6), (7, 8))
            >>> d1 = Iter(d3).flatten().flatten().collect(Seq)
            >>> 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.

        """
        return self._from_iterable(itertools.chain.from_iterable(iter(self)))

    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 Iter, Seq
            >>> Iter((1, 2, 3)).flat_map(lambda x: range(x)).collect(Seq)
            Seq(0, 0, 1, 0, 1, 2)

            ```
        """
        return self._from_iterable(itertools.chain.from_iterable(map(func, iter(self))))

    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 Iter, Some, NONE
            >>> def _parse(s: str) -> Option[int]:
            ...     try:
            ...         return Some(int(s))
            ...     except ValueError:
            ...         return NONE
            >>>
            >>> Iter(["lol", "NaN", "2", "5"]).find_map(_parse)
            Some(2)

            ```
        """
        return self.filter_map(func).next()

    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 `PyoIterator::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`.

        `PyoIterator::map` is conceptually similar to a for loop.

        However, as `PyoIterator::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 `PyoIterator.for_each` than `PyoIterator.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 Iter, Seq
            >>> Iter((1, 2)).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"))
            >>> data.iter().map(str.upper).collect(Seq)
            Seq('A', 'B', 'C')
            >>> data.iter().map(lambda s: s.upper()).collect(Seq)
            Seq('A', 'B', 'C')

            ```
        """
        return self._from_iterable(map(func, iter(self)))

    @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[R](
        self: PyoIterator[tuple[Any, ...]],  # pyright: ignore[reportExplicitAny]
        func: Callable[..., R],
    ) -> PyoIterator[R]: ...
    def map_star[U: AnyIter, R](
        self: PyoIterator[U], func: Callable[..., R]
    ) -> PyoIterator[R]:
        """Applies a function to each element.where each element is an iterable.

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

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

        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 iterable 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"))
            >>> data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
            Seq('blue-S', 'blue-M', 'red-S', 'red-M')
            >>> # This is equivalent to:
            >>> data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
            Seq('blue-S', 'blue-M', 'red-S', 'red-M')

            ```
        """
        return self._from_iterable(itertools.starmap(func, iter(self)))

    @overload
    def map_with[T1, R](
        self, iterable: Iterable[T1], /, *, func: Callable[[T, T1], R]
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, R](
        self,
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        /,
        *,
        func: Callable[[T, T1, T2], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, R](
        self,
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        /,
        *,
        func: Callable[[T, T1, T2, T3], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, T4, R](
        self,
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
        *,
        func: Callable[[T, T1, T2, T3, T4], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[T1, T2, T3, T4, T5, R](
        self,
        iterable: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        iter5: Iterable[T5],
        /,
        *,
        func: Callable[[T, T1, T2, T3, T4, T5], R],
    ) -> PyoIterator[R]: ...
    @overload
    def map_with[R](
        self,
        iterable: AnyIter,
        iter2: AnyIter,
        iter3: AnyIter,
        iter4: AnyIter,
        iter5: AnyIter,
        iter6: AnyIter,
        /,
        *iterables: AnyIter,
        func: Callable[..., R],
    ) -> PyoIterator[R]: ...
    def map_with[R](
        self, *iterables: AnyIter, func: Callable[..., R]
    ) -> 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:
            *iterables (AnyIter): Additional iterables to zip with **self**.
            func (Callable[..., R]): Function to apply to the elements of the iterables.

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

        See Also:
            [`PyoIterator::map_juxt`][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(y, z, func=Triangle).collect(Seq)
            >>> output
            Seq(Triangle(x=1, y=4, z=7), Triangle(x=2, y=5, z=8), Triangle(x=3, y=6, z=9))

            ```
        """
        return self._from_iterable(map(func, iter(self), *iterables))

    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 as an argument.

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

        After `NONE` is returned, `PyoIterator::map_while` stops and the rest of the elements are ignored.

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

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

        Example:
            ```python
            >>> from pyochain import Iter, Some, NONE, Seq
            >>>
            >>> def checked_div(x: int) -> Option[int]:
            ...     return Some(16 // x) if x != 0 else NONE
            >>>
            >>> data = Iter((-1, 4, 0, 1))
            >>> data.map_while(checked_div).collect(Seq)
            Seq(-16, 4)
            >>> data = Iter((0, 1, 2, -3, 4, 5, -6))
            >>> # Convert to positive ints, stop at first negative
            >>> data.map_while(lambda x: Some(x) if x >= 0 else NONE).collect(Seq)
            Seq(0, 1, 2)

            ```
        """
        return self._from_iterable(tls.MapWhile(iter(self), func))

    def repeat(self, n: int | None = None) -> PyoIterator[PyoIterator[T]]:
        """Repeat the entire `Iterator` **n** times (as elements).

        If **n** is `None`, repeat indefinitely.

        Operates lazily, hence if you need to get the underlying elements, you will need to collect each repeated `Iterator` via `.map(lambda x: x.collect(Seq))` or similar.

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

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

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

        Args:
            n (int | None): Optional number of repetitions.

        Returns:
            PyoIterator[PyoIterator[T]]: An `Iterator` of repeated `Iterator`s.

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

            ```
        """
        new = self._from_iterable

        def _repeat_infinite() -> Generator[PyoIterator[T]]:
            tee = functools.partial(itertools.tee, iter(self), 1)
            iterators = tee()
            while True:
                yield new(iterators[0])
                iterators = tee()

        match n:
            case None:
                return new(_repeat_infinite())
            case _:
                return new(map(new, itertools.tee(iter(self), n)))

    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
            >>>
            >>> 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
            >>> Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
            Seq(1, 3, 6, 10)

            ```
        """
        return self._from_iterable(tls.Scan(iter(self), initial, func))

    @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], bool] | None) -> PyoIterator[T]: ...
    def filter[R, N](
        self, func: FilterFn[T, R] = None
    ) -> PyoIterator[T] | PyoIterator[R] | PyoIterator[N]:
        """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:
            `Iter.filter(f).next()` is equivalent to `Iter.find(f)`.

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

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

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> data = (1, 2, 3)
            >>> Iter(data).filter(lambda x: x > 1).collect(Seq)
            Seq(2, 3)
            >>> # See the equivalence of next and find:
            >>> Iter(data).filter(lambda x: x > 1).next()
            Some(2)
            >>> 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")
            >>> Iter(mixed_data).filter(_is_str).collect(Seq)
            Seq('two', 'four')
            >>> maybe_none = (1, None, 3, None)
            >>> Iter(maybe_none).filter().collect(Seq)
            Seq(1, 3)
            >>> maybe_false = (0, 1, False, 2, "", 3, None)
            >>> Iter(maybe_false).filter().collect(Seq)
            Seq(1, 2, 3)

            ```
        """
        return self._from_iterable(filter(func, iter(self)))

    @overload
    def filter_star[T1](
        self: PyoIterator[tuple[T1]], func: Callable[[T1], bool]
    ) -> PyoIterator[tuple[T1]]: ...
    @overload
    def filter_star[T1, T2](
        self: PyoIterator[tuple[T1, T2]],
        func: Callable[[T1, T2], bool],
    ) -> PyoIterator[tuple[T1, T2]]: ...
    @overload
    def filter_star[T1, T2, T3](
        self: PyoIterator[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> 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], bool],
    ) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]]: ...

    def filter_star[U: tuple[Any, ...]](
        self: PyoIterator[U], func: Callable[..., bool]
    ) -> 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[..., bool]): 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)
            ... )
            >>> output
            Seq('Apple', 'Cherry')

            ```
        """
        return self._from_iterable(tls.FilterStar(iter(self), func))

    @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], bool]) -> PyoIterator[T]: ...
    def filter_false[U](
        self, func: FilterFn[T, U] = None
    ) -> PyoIterator[T] | PyoIterator[U]:
        """Return elements for which **func** is `False`.

        The **func** can return a `TypeIs` to narrow the type of the returned `Iterator`.

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

        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 Iter, Seq
            >>> Iter((1, 2, 3)).filter_false(lambda x: x > 1).collect(Seq)
            Seq(1,)

            ```
        """
        return self._from_iterable(itertools.filterfalse(func, iter(self)))

    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:
            [`PyoIterator::filter`][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)
            >>> 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)
            ... )
            >>> parsed
            Seq(1, 5)

            ```
        """
        return self._from_iterable(tls.FilterMap(iter(self), func))

    @overload
    def filter_map_star[R](
        self: PyoIterator[tuple[Any]],  # pyright: ignore[reportExplicitAny]
        func: Callable[[Any], Option[R]],  # pyright: ignore[reportExplicitAny]
    ) -> 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: AnyIter, 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 Iter, Result, Ok, Err, Seq
            >>> data = (("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 = (
            ...     Iter(data)
            ...     .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
            ...     .collect(Seq)
            ... )
            >>> parsed
            Seq((1, 10),)

            ```
        """
        return self._from_iterable(tls.FilterMapStar(iter(self), func))

    @overload
    def zip[T1](
        self,
        iter1: Iterable[T1],
        /,
        *,
        strict: bool = ...,
    ) -> PyoIterator[tuple[T, T1]]: ...
    @overload
    def zip[T1, T2](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        /,
        *,
        strict: bool = ...,
    ) -> PyoIterator[tuple[T, T1, T2]]: ...
    @overload
    def zip[T1, T2, T3](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        /,
        *,
        strict: bool = ...,
    ) -> PyoIterator[tuple[T, T1, T2, T3]]: ...
    @overload
    def zip[T1, T2, T3, T4](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
        *,
        strict: bool = ...,
    ) -> PyoIterator[tuple[T, T1, T2, T3, T4]]: ...
    def zip(
        self, *others: AnyIter, strict: bool = False
    ) -> PyoIterator[tuple[Any, ...]]:  # pyright: ignore[reportExplicitAny]
        """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:
            `Iter.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 (AnyIter): 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 Iter, Seq
            >>>
            >>> Iter((1, 2)).zip((10, 20)).collect(Seq)
            Seq((1, 10), (2, 20))
            >>> Iter(("a", "b")).zip((1, 2, 3)).collect(Seq)
            Seq(('a', 1), ('b', 2))

            ```
        """
        return self._from_iterable(zip(iter(self), *others, strict=strict))

    @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],
        ]
    ]: ...
    @overload
    def zip_longest(
        self,
        iter2: Iterable[T],
        iter3: Iterable[T],
        iter4: Iterable[T],
        iter5: Iterable[T],
        iter6: Iterable[T],
        /,
        *iterables: AnyIter,
    ) -> PyoIterator[tuple[Option[T], ...]]: ...
    def zip_longest(self, *others: AnyIter) -> ZippedLongest[T]:
        """Return a zip Iterator who yield a tuple where the i-th element comes from the i-th iterable argument.

        Yield values until the longest iterable in the argument sequence is exhausted, and then it raises StopIteration.

        The longest iterable determines the length of the returned iterator, and will return `Some[T]` until exhaustion.

        When the shorter iterables are exhausted, they yield `NONE`.

        Args:
            *others (AnyIter): Other iterables to zip with.

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

        Example:
            ```python
            >>> from pyochain import Iter, Some, NONE, Vec
            >>> Iter((1, 2)).zip_longest([10]).collect(Vec)
            Vec((Some(1), Some(10)), (Some(2), NONE))
            >>> # Can be combined with try collect to filter out the NONE:
            >>> zipped = (
            ...     Iter((1, 2))
            ...     .zip_longest([10])
            ...     .map(lambda x: Iter(x).try_collect())
            ...     .collect(Vec)
            ... )
            >>> zipped
            Vec(Some(Vec(1, 10)), NONE)

            ```
        """
        return self._from_iterable(
            tuple(option(t) for t in tup)
            for tup in itertools.zip_longest(iter(self), *others, fillvalue=None)
        )

    def unzip[U, V](
        self: PyoIterator[tuple[U, V]],
    ) -> tuple[PyoIterator[U], PyoIterator[V]]:
        """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:
            tuple[PyoIterator[U], PyoIterator[V]]: A tuple containing two iterators, one for each element of the pairs.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> data = ((1, "a"), (2, "b"), (3, "c"))
            >>> left, right = Iter(data).unzip()
            >>> left.collect(Seq)
            Seq(1, 2, 3)
            >>> right.collect(Seq)
            Seq('a', 'b', 'c')

            ```
        """
        left, right = itertools.tee(iter(self), 2)
        return self._from_iterable(x[0] for x in left), self._from_iterable(
            x[1] for x in right
        )

    @overload
    def product(self) -> PyoIterator[tuple[T]]: ...
    @overload
    def product[T1](self, iter1: Iterable[T1], /) -> PyoIterator[tuple[T, T1]]: ...
    @overload
    def product[T1, T2](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        /,
    ) -> PyoIterator[tuple[T, T1, T2]]: ...
    @overload
    def product[T1, T2, T3](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        /,
    ) -> PyoIterator[tuple[T, T1, T2, T3]]: ...
    @overload
    def product[T1, T2, T3, T4](
        self,
        iter1: Iterable[T1],
        iter2: Iterable[T2],
        iter3: Iterable[T3],
        iter4: Iterable[T4],
        /,
    ) -> PyoIterator[tuple[T, T1, T2, T3, T4]]: ...

    def product(self, *others: AnyIter) -> PyoIterator[tuple[Any, ...]]:  # pyright: ignore[reportExplicitAny]
        """Computes the Cartesian product with another iterable.

        This is the declarative equivalent of nested for-loops.

        It pairs every element from the source iterable with every element from the
        other iterable.

        Args:
            *others (AnyIter): Other iterables to compute the Cartesian product with.

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

        Example:
            ```python
            >>> from pyochain import Seq, Range, Iter
            >>>
            >>> data = Seq(("blue", "red"))
            >>> data.iter().product(["S", "M"]).collect(Seq)
            Seq(('blue', 'S'), ('blue', 'M'), ('red', 'S'), ('red', 'M'))
            >>> res = (
            ...     data
            ...     .iter()
            ...     .product(["S", "M"])
            ...     .map_star(lambda color, size: f"{color}-{size}")
            ...     .collect(Seq)
            ... )
            >>> res
            Seq('blue-S', 'blue-M', 'red-S', 'red-M')
            >>> res = (
            ...     Range(1, 4)
            ...     .iter()
            ...     .product([10, 20])
            ...     .filter_star(lambda a, b: a * b >= 40)
            ...     .map_star(lambda a, b: a * b)
            ...     .collect(Seq)
            ... )
            >>> res
            Seq(40, 60)
            >>> res = (
            ...     Iter
            ...     .once(1)
            ...     .product(["a", "b"], [True])
            ...     .filter_star(lambda _a, b, _c: b != "a")
            ...     .map_star(lambda a, b, c: f"{a}{b} is {c}")
            ...     .collect(Seq)
            ... )
            >>> res
            Seq('1b is True',)

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

    @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],  # pyright: ignore[reportExplicitAny]
    ) -> 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:
            [`PyoIterator::map_windows_star`][map_windows_star] for a version that unpacks the window into separate arguments.

        Example:
            ```python
            >>> from pyochain import Iter, Seq, Range
            >>> import statistics
            >>> Iter((1, 2, 3, 4)).map_windows(2, statistics.mean).collect(Seq)
            Seq(1.5, 2.5, 3.5)
            >>> joined = (
            ...     Iter("abcd")
            ...     .map_windows(3, lambda window: "".join(window).upper())
            ...     .collect(Seq)
            ... )
            >>> joined
            Seq('ABC', 'BCD')
            >>> sum_windows = Range(0, 5).iter().map_windows(4, sum).collect(Seq)
            >>> sum_windows
            Seq(6, 10)

            ```
        """
        return self._from_iterable(map(func, tls.SlidingWindow(iter(self), length)))

    @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:
            [`PyoIterator::map_windows`][map_windows] for a version that passes the entire window as a single tuple argument.

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
            Seq('a+b', 'b+c', 'c+d')
            >>> Iter([1, 2, 3, 4]).map_windows_star(2, lambda x, y: x + y).collect(Seq)
            Seq(3, 5, 7)

            ```
        """
        return self._from_iterable(
            itertools.starmap(func, tls.SlidingWindow(iter(self), length))
        )

    def batch(self, n: int, *, strict: bool = False) -> PyoIterator[tuple[T, ...]]:
        """Batch elements into tuples of length n and return a new Iter.

        - 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 input iterable is exhausted.

        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 Iter, Seq
            >>> Iter("ABCDEFG").batch(3).collect(Seq)
            Seq(('A', 'B', 'C'), ('D', 'E', 'F'), ('G',))

            ```
        """
        return self._from_iterable(itertools.batched(iter(self), n, strict=strict))

    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:
            `PyoIterator::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:
            start (int): The starting index.

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

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>> data = ("apple", "banana", "cherry")
            >>> output = Iter(data).enumerate().collect(Seq)
            >>> output
            Seq((0, 'apple'), (1, 'banana'), (2, 'cherry'))
            >>> output = (
            ...     Iter(data)
            ...     .enumerate()
            ...     .map_star(lambda idx, val: (idx, val.upper()))
            ...     .collect(Seq)
            ... )
            >>> output
            Seq((0, 'APPLE'), (1, 'BANANA'), (2, 'CHERRY'))

            ```
        """
        return self._from_iterable(enumerate(iter(self), start))

    @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 all combinations of length r.

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

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

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

            ```
        """
        return self._from_iterable(itertools.combinations(iter(self), r))

    @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 all permutations of length r.

        Args:
            r (int | None): Length of each permutation. Defaults to the length of the iterable.

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

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

            ```
        """
        return self._from_iterable(itertools.permutations(iter(self), r))

    @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 all combinations with replacement of length r.

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

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

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

            ```
        """
        return self._from_iterable(
            itertools.combinations_with_replacement(iter(self), r)
        )

    def pairwise(self) -> PyoIterator[tuple[T, T]]:
        """Return an iterator over pairs of consecutive elements.

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

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

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

    @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, ...]]:  # pyright: ignore[reportExplicitAny]
        """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 `PyoIterator::{for_each, fold}` with mutable collections, or `PyoIterator::map` followed by `PyoIterator::zip` to combine the results.

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

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

        Example:
            ```python
            >>> from pyochain import Iter, Seq
            >>>
            >>> def is_even(n: int) -> bool:
            ...     return n % 2 == 0
            >>> def is_positive(n: int) -> bool:
            ...     return n > 0
            >>>
            >>> Iter([1, -2, 3]).map_juxt(is_even, is_positive).collect(Seq)
            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
            >>> def curried_add(a: int) -> Callable[[int], int]:
            ...     def fn(b: int) -> int:
            ...         return a + b
            ...
            ...     return fn
            >>>
            >>> Iter((1, 2, 3)).map_juxt(curried_add(10), curried_add(20)).collect(Seq)
            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
            >>> from pyochain import Range
            >>> res = (
            ...     Range(0, 5)
            ...     .iter()
            ...     .map_juxt(lambda x: x * 2, lambda x: x**2)
            ...     .filter_star(lambda double, square: double + square <= 5)
            ...     .collect(Seq)
            ... )
            >>> res
            Seq((0, 0), (2, 1))

            ```
        """
        return self._from_iterable(map(tls.Juxt(*funcs), iter(self)))

    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"))
            >>> data.iter().with_position().collect(Seq)
            Seq(('first', 'a'), ('middle', 'b'), ('middle', 'c'), ('last', 'd'))
            >>> data.iter().take(1).with_position().collect(Seq)
            Seq(('only', 'a'),)
            >>> data.iter().take(2).with_position().collect(Seq)
            Seq(('first', 'a'), ('last', 'b'))

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

    @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,  # pyright: ignore[reportExplicitAny]
    ) -> PyoIterator[tuple[Any | T, PyoIterator[T]]]:  # pyright: ignore[reportExplicitAny]
        """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 not specified or is None, **key** defaults to an identity function and returns the element unchanged.

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

        Example:
            `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
            >>> (
            ...     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)
            ... )
            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 Iter
            >>> data = (
            ...     {"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 = (
            ...     Iter(data)
            ...     .group_by(lambda x: x["gender"])
            ...     .map_star(lambda g, vals: (g, vals.count()))
            ...     .collect(Seq)
            ... )
            >>> output
            Seq(('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 Iter
            >>> groups = (
            ...     Iter(("a1", "a2", "b1"))
            ...     .group_by(lambda x: x[0])
            ...     .collect(Seq)
            ...     .iter()
            ...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
            ...     .collect(Seq)
            ... )
            >>> groups
            Seq(('a', Seq()), ('b', Seq()))

            ```
            As such, the correct pattern is the following:
            ```python
            >>> from pyochain import Iter
            >>> groups = (
            ...     Iter(("a1", "a2", "b1", "b2"))
            ...     .group_by(lambda x: x[0])
            ...     # ✅ Materialize NOW
            ...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
            ...     .collect(Seq)
            ... )
            >>> groups
            Seq(('a', Seq('a1', 'a2')), ('b', Seq('b1', 'b2')))

            ```
        """
        new = self._from_iterable
        return new((x, new(y)) for x, y in itertools.groupby(iter(self), key))

accumulate(func, initial=None)

Return an Iterator of accumulated binary function results.

In principle, PyoIterator::accumulate is similar to PyoIterator::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 PyoIterator::accumulate is what would have been returned by PyoIterator::fold if it had been used instead.

Parameters:

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

A binary function to apply cumulatively.

required
initial T | None

Optional initial value to start the accumulation.

None

Returns:

Type Description
PyoIterator[T]

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

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).accumulate(lambda a, b: a + b, 0).collect(Seq)
Seq(0, 1, 3, 6)
>>> # The final accumulated result is the same as fold:
>>> Iter((1, 2, 3)).fold(0, lambda a, b: a + b)
6
>>> Iter((1, 2, 3)).accumulate(lambda a, b: a * b).collect(Seq)
Seq(1, 2, 6)
Source code in src/pyochain/abc/_iterator.py
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
def accumulate(
    self, func: Callable[[T, T], T], initial: T | None = None
) -> PyoIterator[T]:
    """Return an `Iterator` of accumulated binary function results.

    In principle, `PyoIterator::accumulate` is similar to `PyoIterator::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 `PyoIterator::accumulate` is what would have been returned by `PyoIterator::fold` if it had been used instead.

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

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

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

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

all(predicate=None)

Tests if every element of the Iterator is truthy.

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

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

If any of them return false, it returns false.

An empty Iterator returns true.

Parameters:

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

Optional function to evaluate each item.

None

Returns:

Name Type Description
bool bool

True if all elements match the predicate, False otherwise.

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

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

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

    If any of them return false, it returns false.

    An empty `Iterator` returns true.

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

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

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, True)).all()
        True
        >>> Iter(()).all()
        True
        >>> Iter((1, 0)).all()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>>
        >>> Iter((2, 4, 6)).all(is_even)
        True
        >>> Iter(("a", "", "c")).all()
        False
        >>> Iter((1, None, 3)).all()
        False

        ```
    """
    if predicate is None:
        return all(iter(self))
    return tls.all(iter(self), predicate)

all_equal(key=None)

Return True if all items of the Iterator are equal.

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

Credits to more-itertools for the implementation.

Parameters:

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

Function to transform items before comparison.

None

Returns:

Name Type Description
bool bool

True if all items are equal, False otherwise.

Example
>>> from pyochain import Iter, Range
>>> Iter("AaaA").all_equal(key=str.casefold)
True
>>> Range(0, 9).iter().all_equal(key=lambda x: x < 10)
True
Source code in src/pyochain/abc/_iterator.py
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
def all_equal[U](self, key: Callable[[T], U] | None = None) -> bool:
    """Return `True` if all items of the `Iterator` are equal.

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

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

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

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

    Example:
        ```python
        >>> from pyochain import Iter, Range
        >>> Iter("AaaA").all_equal(key=str.casefold)
        True
        >>> Range(0, 9).iter().all_equal(key=lambda x: x < 10)
        True

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

all_unique()

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

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

Elements are assumed to be hashable.

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

Tip

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

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

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

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

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

Returns:

Name Type Description
bool bool

True if all elements are unique, False otherwise.

Example
>>> from pyochain import Iter, Seq, Set
>>> Iter("ABCB").all_unique()
False
>>> Iter("ABCb").all_unique()
True
>>> # Alternative way to check uniqueness by comparing lengths:
>>> collection = Seq((1, 2, 3, 3))
>>> collection.len() == collection.pipe(Set).len()
False
Source code in src/pyochain/abc/_iterator.py
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
def all_unique[U](self) -> bool:
    """Returns `True` if all the elements of the `Iterator` are unique.

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

    Elements are assumed to be hashable.

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

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

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

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

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

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

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

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

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

all_unique_by(key)

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

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

Credits to more-itertools for the implementation.

Parameters:

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

Function to transform items before comparison.

required

Returns:

Name Type Description
bool bool

True if all elements are unique, False otherwise.

Example
>>> from pyochain import Iter
>>> Iter("ABCb").all_unique()
True
>>> Iter("ABCb").all_unique_by(str.lower)
False
Source code in src/pyochain/abc/_iterator.py
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
def all_unique_by[U](self, key: Callable[[T], U]) -> bool:
    """Returns True if all the elements of **self** transformed by **key** are unique.

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

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

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

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

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

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

any(predicate=None)

Tests if any element of the Iterator is truthy.

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

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

If they all return false, it returns false.

An empty Iterator returns false.

Parameters:

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

Optional function to evaluate each item.

None

Returns:

Name Type Description
bool bool

True if any element matches the predicate, False otherwise.

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

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

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

    If they all return false, it returns false.

    An empty `Iterator` returns false.

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

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

    Example:
        ```python
        >>> from pyochain import Iter, Range
        >>> Iter((0, 1)).any()
        True
        >>> Range(0, 0).iter().any()
        False
        >>> def is_even(x: int) -> bool:
        ...     return x % 2 == 0
        >>> Iter((1, 3, 4)).any(is_even)
        True

        ```
    """
    if predicate is None:
        return any(iter(self))
    return tls.any(iter(self), predicate)

arg_max()

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

Credits to more-itertools for the implementation.

Returns:

Name Type Description
int int

The index of the maximum value.

Example

Basic usage:

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

Source code in src/pyochain/abc/_iterator.py
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
def arg_max(self) -> int:
    """Index of the first occurrence of a maximum value in the `Iterator`.

    Credits to more-itertools for the implementation.

    Returns:
        int: The index of the maximum value.

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

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

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

arg_max_by(key)

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

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

Credits to more-itertools for the implementation.

Parameters:

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

Function to determine the value for comparison.

required

Returns:

Name Type Description
int int

The index of the maximum value.

Example

Basic usage:

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

Source code in src/pyochain/abc/_iterator.py
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
def arg_max_by[U](self, key: Callable[[T], U]) -> int:
    """Index of the first occurrence of a maximum value in the `Iterator` based on a *key* function.

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

    Credits to more-itertools for the implementation.

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

    Returns:
        int: The index of the maximum value.

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

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

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

arg_min()

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

Credits to more-itertools for the implementation.

Returns:

Name Type Description
int int

The index of the minimum value.

Example
>>> from pyochain import Iter, Seq
>>> # Example 1: Basic usage
>>> Iter("efghabcdijkl").arg_min()
4
>>> Iter((3, 2, 1, 0, 4, 2, 1, 0)).arg_min()
3
Source code in src/pyochain/abc/_iterator.py
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
def arg_min(self) -> int:
    """Index of the first occurrence of a minimum value in the `Iterator`.

    Credits to more-itertools for the implementation.

    Returns:
        int: The index of the minimum value.

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

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

arg_min_by(key)

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

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

Credits to more-itertools for the implementation.

Parameters:

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

Function to determine the value for comparison.

required

Returns:

Name Type Description
int int

The index of the minimum value.

Example

Basic usage:

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

Source code in src/pyochain/abc/_iterator.py
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
def arg_min_by[U](self, key: Callable[[T], U]) -> int:
    """Index of the first occurrence of a minimum value in the `Iterator` based on a *key* function.

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

    Credits to more-itertools for the implementation.

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

    Returns:
        int: The index of the minimum value.

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

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

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

array_chunks(size)

Yield subiterators (chunks) that each yield a fixed number elements, determined by size.

The last chunk will be shorter if there are not enough elements.

Parameters:

Name Type Description Default
size int

Number of elements in each chunk.

required

Returns:

Type Description
PyoIterator[PyoIterator[T]]

PyoIterator[PyoIterator[T]]: An iterable of iterators, each yielding n elements.

If the sub-iterables are read in order, the elements of iterable won't be stored in memory.

If they are read out of order, :func:itertools.tee is used to cache elements as necessary.

Example

>>> from pyochain import Iter, Seq
>>> all_chunks = Iter.from_count().array_chunks(4)
>>> c_1, c_2, c_3 = all_chunks.next(), all_chunks.next(), all_chunks.next()
>>> # c_1's elements have been cached; c_3's haven't been
>>> c_2.unwrap().collect(Seq)
Seq(4, 5, 6, 7)
>>> c_1.unwrap().collect(Seq)
Seq(0, 1, 2, 3)
>>> c_3.unwrap().collect(Seq)
Seq(8, 9, 10, 11)
You can collect the chunks into a collection of collections, for example:
>>> from pyochain import Seq
>>> from pyochain.abc import PyoIterable
>>> def collect_all_chunks(data: PyoIterable[int]) -> Seq[Seq[int]]:
...     return (
...         data
...         .iter()
...         .array_chunks(3)
...         .map(lambda c: c.collect(Seq))
...         .collect(Seq)
...     )
>>> Seq((1, 2, 3, 4, 5, 6)).pipe(collect_all_chunks)
Seq(Seq(1, 2, 3), Seq(4, 5, 6))
>>> Seq((1, 2, 3, 4, 5, 6, 7, 8)).pipe(collect_all_chunks)
Seq(Seq(1, 2, 3), Seq(4, 5, 6), Seq(7, 8))

Source code in src/pyochain/abc/_iterator.py
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
def array_chunks(self, size: int) -> PyoIterator[PyoIterator[T]]:
    """Yield subiterators (chunks) that each yield a fixed number elements, determined by size.

    The last chunk will be shorter if there are not enough elements.

    Args:
        size (int): Number of elements in each chunk.

    Returns:
        PyoIterator[PyoIterator[T]]: An iterable of iterators, each yielding n elements.

    If the sub-iterables are read in order, the elements of *iterable*
    won't be stored in memory.

    If they are read out of order, :func:`itertools.tee` is used to cache
    elements as necessary.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> all_chunks = Iter.from_count().array_chunks(4)
        >>> c_1, c_2, c_3 = all_chunks.next(), all_chunks.next(), all_chunks.next()
        >>> # c_1's elements have been cached; c_3's haven't been
        >>> c_2.unwrap().collect(Seq)
        Seq(4, 5, 6, 7)
        >>> c_1.unwrap().collect(Seq)
        Seq(0, 1, 2, 3)
        >>> c_3.unwrap().collect(Seq)
        Seq(8, 9, 10, 11)

        ```
        You can collect the chunks into a collection of collections, for example:
        ```python
        >>> from pyochain import Seq
        >>> from pyochain.abc import PyoIterable
        >>> def collect_all_chunks(data: PyoIterable[int]) -> Seq[Seq[int]]:
        ...     return (
        ...         data
        ...         .iter()
        ...         .array_chunks(3)
        ...         .map(lambda c: c.collect(Seq))
        ...         .collect(Seq)
        ...     )
        >>> Seq((1, 2, 3, 4, 5, 6)).pipe(collect_all_chunks)
        Seq(Seq(1, 2, 3), Seq(4, 5, 6))
        >>> Seq((1, 2, 3, 4, 5, 6, 7, 8)).pipe(collect_all_chunks)
        Seq(Seq(1, 2, 3), Seq(4, 5, 6), Seq(7, 8))

        ```
    """
    from collections import deque
    from contextlib import suppress

    def _chunks() -> Iterator[PyoIterator[T]]:
        def _ichunk(
            iterator: Iterator[T], n: int
        ) -> tuple[Iterator[T], Callable[[int], int]]:
            cache: deque[T] = deque()
            chunk = itertools.islice(iterator, n)

            def _generator() -> Iterator[T]:
                with suppress(StopIteration):
                    while True:
                        if cache:
                            yield cache.popleft()
                        else:
                            yield next(chunk)

            def _materialize_next(n: int) -> int:
                to_cache = n - len(cache)

                # materialize up to n
                if to_cache > 0:
                    cache.extend(itertools.islice(chunk, to_cache))

                # return number materialized up to n
                return min(n, len(cache))

            return (_generator(), _materialize_next)

        new = self._from_iterable
        while True:
            # Create new chunk
            chunk, materialize_next = _ichunk(iter(self), size)

            # Check to see whether we're at the end of the source iterable
            if not materialize_next(size):
                return

            yield new(chunk)
            _ = materialize_next(size)

    return self._from_iterable(_chunks())

batch(n, *, strict=False)

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

  • 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 input iterable is exhausted.

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 Iter, Seq
>>> Iter("ABCDEFG").batch(3).collect(Seq)
Seq(('A', 'B', 'C'), ('D', 'E', 'F'), ('G',))
Source code in src/pyochain/abc/_iterator.py
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
def batch(self, n: int, *, strict: bool = False) -> PyoIterator[tuple[T, ...]]:
    """Batch elements into tuples of length n and return a new Iter.

    - 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 input iterable is exhausted.

    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 Iter, Seq
        >>> Iter("ABCDEFG").batch(3).collect(Seq)
        Seq(('A', 'B', 'C'), ('D', 'E', 'F'), ('G',))

        ```
    """
    return self._from_iterable(itertools.batched(iter(self), n, strict=strict))

chain(*others)

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

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

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

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

See Also

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

Parameters:

Name Type Description Default
*others Iterable[T]

Other iterables to concatenate.

()

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: A new Iterator which will first iterate over values from the original Iterator and then over values from the others Iterables.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2)).chain((3, 4), [5]).collect(Seq)
Seq(1, 2, 3, 4, 5)
>>> Iter((1, 2)).chain(Iter.from_count(3)).take(5).collect(Seq)
Seq(1, 2, 3, 4, 5)
Source code in src/pyochain/abc/_iterator.py
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
def chain(self, *others: Iterable[T]) -> PyoIterator[T]:
    """Concatenate **self** with one or more `Iterables`, any of which may be infinite.

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

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

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

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

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

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

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

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

collect(collector)

Transforms the Iterator into a collection.

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

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

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

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

This is equivalent to 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(0, 5)
>>> data.iter().collect(list)
[0, 1, 2, 3, 4]
>>> data.iter().collect(Vec)
Vec(0, 1, 2, 3, 4)
>>> data.iter().map(str).enumerate().collect(Dict)
Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')
Sometimes type checkers can't infer the type of the collector, in which case you can use an explicit type annotation to help them out.

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

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

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

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

Source code in src/pyochain/abc/_iterator.py
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
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(0, 5)
        >>> data.iter().collect(list)
        [0, 1, 2, 3, 4]
        >>> data.iter().collect(Vec)
        Vec(0, 1, 2, 3, 4)
        >>> data.iter().map(str).enumerate().collect(Dict)
        Dict(0: '0', 1: '1', 2: '2', 3: '3', 4: '4')

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

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

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

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

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

collect_into(collection)

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

Collects all the items from the Iterator into a MutableSequence.

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

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

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

Parameters:

Name Type Description Default
collection MutableSequence[T]

A mutable collection to collect items into.

required

Returns:

Type Description
MutableSequence[T]

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

Example

Basic usage:

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

Source code in src/pyochain/abc/_iterator.py
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
def collect_into(self, collection: MutableSequence[T]) -> MutableSequence[T]:
    """Collects all the items from the `Iterator` into a `MutableSequence`.

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

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

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

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

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

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

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

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

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 all combinations of length r.

Parameters:

Name Type Description Default
r int

Length of each combination.

required

Returns:

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

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

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).combinations(2).collect(Seq)
Seq((1, 2), (1, 3), (2, 3))
Source code in src/pyochain/abc/_iterator.py
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
def combinations(self, r: int) -> PyoIterator[tuple[T, ...]]:
    """Return all combinations of length r.

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

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

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

        ```
    """
    return self._from_iterable(itertools.combinations(iter(self), r))

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 all combinations with replacement of length r.

Parameters:

Name Type Description Default
r int

Length of each combination.

required

Returns:

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

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

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).combinations_with_replacement(2).collect(Seq)
Seq((1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3))
Source code in src/pyochain/abc/_iterator.py
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
def combinations_with_replacement(self, r: int) -> PyoIterator[tuple[T, ...]]:
    """Return all combinations with replacement of length r.

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

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

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

        ```
    """
    return self._from_iterable(
        itertools.combinations_with_replacement(iter(self), r)
    )

compress(*selectors)

Filter elements using a boolean selector iterable.

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
>>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect(Seq)
Seq('A', 'C', 'E', 'F')
Source code in src/pyochain/abc/_iterator.py
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
def compress(self, *selectors: bool) -> PyoIterator[T]:
    """Filter elements using a boolean selector iterable.

    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
        >>> Iter("ABCDEF").compress(1, 0, 1, 0, 1, 1).collect(Seq)
        Seq('A', 'C', 'E', 'F')

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

count()

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

Returns:

Name Type Description
int int

The count of elements.

Example
>>> from pyochain import Iter
>>> data = Iter((1, 2, 3))
>>> data.count()
3
>>> # data is now empty
>>> data.count()
0
Source code in src/pyochain/abc/_iterator.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def count(self) -> int:
    """Consume the `Iterator` and return the number of elements it contained.

    Returns:
        int: The count of elements.

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

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

cycle()

Repeat the Iterator indefinitely.

Warning

This creates an infinite Iterator.

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

See Also

PyoIterator::repeat to repeat self as elements (PyoIterator[PyoIterator[T]]).

Returns:

Type Description
PyoIterator[T]

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

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2)).cycle().take(5).collect(Seq)
Seq(1, 2, 1, 2, 1)
Source code in src/pyochain/abc/_iterator.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
def cycle(self) -> PyoIterator[T]:
    """Repeat the `Iterator` indefinitely.

    Warning:
        This creates an infinite `Iterator`.

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

    See Also:
        [`PyoIterator::repeat`][repeat] to repeat *self* as elements (`PyoIterator[PyoIterator[T]]`).

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

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

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

enumerate(start=0)

Return a Iterator of (index, value) pairs.

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

Tip

PyoIterator::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
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 Iter, Seq
>>> data = ("apple", "banana", "cherry")
>>> output = Iter(data).enumerate().collect(Seq)
>>> output
Seq((0, 'apple'), (1, 'banana'), (2, 'cherry'))
>>> output = (
...     Iter(data)
...     .enumerate()
...     .map_star(lambda idx, val: (idx, val.upper()))
...     .collect(Seq)
... )
>>> output
Seq((0, 'APPLE'), (1, 'BANANA'), (2, 'CHERRY'))
Source code in src/pyochain/abc/_iterator.py
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
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:
        `PyoIterator::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:
        start (int): The starting index.

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

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> data = ("apple", "banana", "cherry")
        >>> output = Iter(data).enumerate().collect(Seq)
        >>> output
        Seq((0, 'apple'), (1, 'banana'), (2, 'cherry'))
        >>> output = (
        ...     Iter(data)
        ...     .enumerate()
        ...     .map_star(lambda idx, val: (idx, val.upper()))
        ...     .collect(Seq)
        ... )
        >>> output
        Seq((0, 'APPLE'), (1, 'BANANA'), (2, 'CHERRY'))

        ```
    """
    return self._from_iterable(enumerate(iter(self), start))

eq(other)

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

Comparison is performed element by element.

Two Iterables are equal only if:

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

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True when both iterables yield the same sequence of values.

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

    Comparison is performed element by element.

    Two `Iterable`s are equal only if:

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

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

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

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

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

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

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], bool] | 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

Iter.filter(f).next() is equivalent to Iter.find(f).

Parameters:

Name Type Description Default
func FilterFn[T, R]

Function to evaluate each item.

None

Returns:

Type Description
PyoIterator[T] | PyoIterator[R] | PyoIterator[N]

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

Example
>>> from pyochain import Iter, Seq
>>> data = (1, 2, 3)
>>> Iter(data).filter(lambda x: x > 1).collect(Seq)
Seq(2, 3)
>>> # See the equivalence of next and find:
>>> Iter(data).filter(lambda x: x > 1).next()
Some(2)
>>> 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")
>>> Iter(mixed_data).filter(_is_str).collect(Seq)
Seq('two', 'four')
>>> maybe_none = (1, None, 3, None)
>>> Iter(maybe_none).filter().collect(Seq)
Seq(1, 3)
>>> maybe_false = (0, 1, False, 2, "", 3, None)
>>> Iter(maybe_false).filter().collect(Seq)
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
def filter[R, N](
    self, func: FilterFn[T, R] = None
) -> PyoIterator[T] | PyoIterator[R] | PyoIterator[N]:
    """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:
        `Iter.filter(f).next()` is equivalent to `Iter.find(f)`.

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

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

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> data = (1, 2, 3)
        >>> Iter(data).filter(lambda x: x > 1).collect(Seq)
        Seq(2, 3)
        >>> # See the equivalence of next and find:
        >>> Iter(data).filter(lambda x: x > 1).next()
        Some(2)
        >>> 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")
        >>> Iter(mixed_data).filter(_is_str).collect(Seq)
        Seq('two', 'four')
        >>> maybe_none = (1, None, 3, None)
        >>> Iter(maybe_none).filter().collect(Seq)
        Seq(1, 3)
        >>> maybe_false = (0, 1, False, 2, "", 3, None)
        >>> Iter(maybe_false).filter().collect(Seq)
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(filter(func, iter(self)))

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], bool]) -> PyoIterator[T]

Return elements for which func is False.

The func can return a TypeIs to narrow the type of the returned Iterator.

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

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 Iter, Seq
>>> Iter((1, 2, 3)).filter_false(lambda x: x > 1).collect(Seq)
Seq(1,)
Source code in src/pyochain/abc/_iterator.py
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
def filter_false[U](
    self, func: FilterFn[T, U] = None
) -> PyoIterator[T] | PyoIterator[U]:
    """Return elements for which **func** is `False`.

    The **func** can return a `TypeIs` to narrow the type of the returned `Iterator`.

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

    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 Iter, Seq
        >>> Iter((1, 2, 3)).filter_false(lambda x: x > 1).collect(Seq)
        Seq(1,)

        ```
    """
    return self._from_iterable(itertools.filterfalse(func, iter(self)))

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

PyoIterator::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)
>>> 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)
... )
>>> parsed
Seq(1, 5)
Source code in src/pyochain/abc/_iterator.py
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
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:
        [`PyoIterator::filter`][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)
        >>> 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)
        ... )
        >>> parsed
        Seq(1, 5)

        ```
    """
    return self._from_iterable(tls.FilterMap(iter(self), func))

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 Iter, Result, Ok, Err, Seq
>>> data = (("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 = (
...     Iter(data)
...     .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
...     .collect(Seq)
... )
>>> parsed
Seq((1, 10),)
Source code in src/pyochain/abc/_iterator.py
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
def filter_map_star[U: AnyIter, 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 Iter, Result, Ok, Err, Seq
        >>> data = (("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 = (
        ...     Iter(data)
        ...     .filter_map_star(lambda s1, s2: _parse_pair(s1, s2).ok())
        ...     .collect(Seq)
        ... )
        >>> parsed
        Seq((1, 10),)

        ```
    """
    return self._from_iterable(tls.FilterMapStar(iter(self), func))

filter_star(func)

filter_star(
    func: Callable[[T1], bool],
) -> PyoIterator[tuple[T1]]
filter_star(
    func: Callable[[T1, T2], bool],
) -> PyoIterator[tuple[T1, T2]]
filter_star(
    func: Callable[[T1, T2, T3], bool],
) -> PyoIterator[tuple[T1, T2, T3]]
filter_star(
    func: Callable[[T1, T2, T3, T4], bool],
) -> PyoIterator[tuple[T1, T2, T3, T4]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5], bool],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], bool],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7], bool],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7]]
filter_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], bool],
) -> PyoIterator[tuple[T1, T2, T3, T4, T5, T6, T7, T8]]
filter_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9], bool
    ],
) -> 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], bool
    ],
) -> 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[..., bool]

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)
... )
>>> output
Seq('Apple', 'Cherry')
Source code in src/pyochain/abc/_iterator.py
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
def filter_star[U: tuple[Any, ...]](
    self: PyoIterator[U], func: Callable[..., bool]
) -> 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[..., bool]): 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)
        ... )
        >>> output
        Seq('Apple', 'Cherry')

        ```
    """
    return self._from_iterable(tls.FilterStar(iter(self), func))

find(predicate)

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

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

Parameters:

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

Function to evaluate each item.

required

Returns:

Type Description
Option[T]

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

Example
>>> from pyochain import Iter, Range
>>>
>>> def gt_five(x: int) -> bool:
...     return x > 5
>>>
>>> def gt_nine(x: int) -> bool:
...     return x > 9
>>> data = Range(0, 10)
>>> data.iter().find(predicate=gt_five)
Some(6)
>>> data.iter().find(predicate=gt_nine).unwrap_or("missing")
'missing'
Source code in src/pyochain/abc/_iterator.py
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
def find(self, predicate: Callable[[T], bool]) -> Option[T]:
    """Searches for an element of an iterator that satisfies a `predicate`.

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

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

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

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

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

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 Iter, Some, NONE
>>> def _parse(s: str) -> Option[int]:
...     try:
...         return Some(int(s))
...     except ValueError:
...         return NONE
>>>
>>> Iter(["lol", "NaN", "2", "5"]).find_map(_parse)
Some(2)
Source code in src/pyochain/abc/_iterator.py
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
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 Iter, Some, NONE
        >>> def _parse(s: str) -> Option[int]:
        ...     try:
        ...         return Some(int(s))
        ...     except ValueError:
        ...         return NONE
        >>>
        >>> Iter(["lol", "NaN", "2", "5"]).find_map(_parse)
        Some(2)

        ```
    """
    return self.filter_map(func).next()

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 Iter, Seq
>>> Iter((1, 2, 3)).flat_map(lambda x: range(x)).collect(Seq)
Seq(0, 0, 1, 0, 1, 2)
Source code in src/pyochain/abc/_iterator.py
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
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 Iter, Seq
        >>> Iter((1, 2, 3)).flat_map(lambda x: range(x)).collect(Seq)
        Seq(0, 0, 1, 0, 1, 2)

        ```
    """
    return self._from_iterable(itertools.chain.from_iterable(map(func, iter(self))))

flatten()

flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[U]
flatten() -> PyoIterator[int]
flatten() -> PyoIterator[int]
flatten() -> 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:

Type Description
PyoIterator[Any]

PyoIterator[Any]: An Iterator of flattened elements.

Example

Basic usage:

>>> from pyochain import Iter, Seq
>>> data = ((1, 2, 3, 4), (5, 6))
>>> flattened = Iter(data).flatten().collect(Seq)
>>> flattened
Seq(1, 2, 3, 4, 5, 6)
Mapping and then flattening:
>>> from pyochain import Iter
>>> words = Iter(("alpha", "beta", "gamma"))
>>> merged = words.flatten().collect(Seq)
>>> merged
Seq('a', 'l', 'p', 'h', 'a', 'b', 'e', 't', 'a', 'g', 'a', 'm', 'm', 'a')
Flattening only removes one level of nesting at a time:
>>> from pyochain import Iter
>>> d3 = (((1, 2), (3, 4)), ((5, 6), (7, 8)))
>>> d2 = Iter(d3).flatten().collect(Seq)
>>> d2
Seq((1, 2), (3, 4), (5, 6), (7, 8))
>>> d1 = Iter(d3).flatten().flatten().collect(Seq)
>>> 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 src/pyochain/abc/_iterator.py
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
def flatten[U: AnyIter](self: PyoIterator[U]) -> PyoIterator[Any]:  # pyright: ignore[reportExplicitAny]
    """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[Any]: An `Iterator` of flattened elements.


    Example:
        Basic usage:
        ```python
        >>> from pyochain import Iter, Seq
        >>> data = ((1, 2, 3, 4), (5, 6))
        >>> flattened = Iter(data).flatten().collect(Seq)
        >>> flattened
        Seq(1, 2, 3, 4, 5, 6)

        ```
        Mapping and then flattening:
        ```python
        >>> from pyochain import Iter
        >>> words = Iter(("alpha", "beta", "gamma"))
        >>> merged = words.flatten().collect(Seq)
        >>> merged
        Seq('a', 'l', 'p', 'h', 'a', 'b', 'e', 't', 'a', 'g', 'a', 'm', 'm', 'a')

        ```
        Flattening only removes one level of nesting at a time:
        ```python
        >>> from pyochain import Iter
        >>> d3 = (((1, 2), (3, 4)), ((5, 6), (7, 8)))
        >>> d2 = Iter(d3).flatten().collect(Seq)
        >>> d2
        Seq((1, 2), (3, 4), (5, 6), (7, 8))
        >>> d1 = Iter(d3).flatten().flatten().collect(Seq)
        >>> 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.

    """
    return self._from_iterable(itertools.chain.from_iterable(iter(self)))

fold(init, func)

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

Parameters:

Name Type Description Default
init B

Initial value for the accumulator.

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

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

required

Returns:

Name Type Description
B B

The final accumulated value.

Note

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

Example
>>> from pyochain import Iter
>>> data = (1, 2, 3)
>>> Iter(data).fold(0, lambda acc, x: acc + x)
6
>>> Iter(data).fold(10, lambda acc, x: acc + x)
16
>>> Iter(("a", "b", "c")).fold("", lambda acc, x: acc + x)
'abc'
Source code in src/pyochain/abc/_iterator.py
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
def fold[B](self, init: B, func: Callable[[B, T], B]) -> B:
    """Fold every element of the `Iterator` into an accumulator by applying an operation, returning the final result.

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

    Returns:
        B: The final accumulated value.

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

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

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

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

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

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

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

Parameters:

Name Type Description Default
init B

Initial value for the accumulator.

required
func Callable[..., B]

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

required
*args P.args

Additional positional arguments to pass to func.

()
**kwargs P.kwargs

Additional keyword arguments to pass to func.

{}

Returns:

Name Type Description
B B

The final accumulated value.

Note

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

Example
>>> from pyochain import Iter
>>>
>>> data = ((1, 2), (3, 4))
>>> Iter(data).fold_star(0, lambda acc, x, y: acc + x + y)
10
>>> data = (("a", "b"), ("c", "d"))
>>> Iter(data).fold_star("", lambda acc, x, y: acc + x + y)
'abcd'
Source code in src/pyochain/abc/_iterator.py
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
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 `PyoIterator::reduce` but with an initial value.

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

        ```
    """

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

    return functools.reduce(_reducer, iter(self), init)

for_each(func, *args, **kwargs)

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

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

Parameters:

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

Function to apply to each element.

required
*args P.args

Positional arguments for the function.

()
**kwargs P.kwargs

Keyword arguments for the function.

{}
Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).for_each(lambda x: print(x + 1))
2
3
4
Source code in src/pyochain/abc/_iterator.py
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
def for_each[**P](
    self,
    func: Callable[Concatenate[T, P], Any],  # pyright: ignore[reportExplicitAny]
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """Consume the `Iterator` by applying a function to each element in the `Iterable`.

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

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

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

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

for_each_star(func, *args, **kwargs)

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

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

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

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

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

Parameters:

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

Function to apply to each unpacked element.

required
*args P.args

Positional arguments for the function.

()
**kwargs P.kwargs

Keyword arguments for the function.

{}
Example
>>> from pyochain import Iter
>>> Iter(((1, 2), (3, 4))).for_each_star(lambda x, y: print(x + y))
3
7
Source code in src/pyochain/abc/_iterator.py
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
def for_each_star[U: tuple[Any, ...], **P, R](
    self: PyoIterator[U],
    func: Callable[..., R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """Consume the `Iterator` by applying a function to each unpacked item in the `Iterable` element.

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

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

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

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

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

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

from_count(start=0, step=1) classmethod

Create an Iterator of evenly spaced values.

Warning

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

Be sure to use PyoIterator::take or PyoIterator::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 sequence.

0
step int

Difference between consecutive values.

1

Returns:

Type Description
PyoIterator[int]

PyoIterator[int]: An Iterator generating the sequence.

Example
>>> from pyochain import Iter, Seq
>>> Iter.from_count(10, 2).take(3).collect(Seq)
Seq(10, 12, 14)
Source code in src/pyochain/abc/_iterator.py
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
@classmethod
def from_count(cls, start: int = 0, step: int = 1) -> PyoIterator[int]:
    """Create an `Iterator` of evenly spaced values.

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

        Be sure to use `PyoIterator::take` or `PyoIterator::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 sequence.
        step (int): Difference between consecutive values.

    Returns:
        PyoIterator[int]: An `Iterator` generating the sequence.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter.from_count(10, 2).take(3).collect(Seq)
        Seq(10, 12, 14)

        ```
    """
    return cls._from_iterable(itertools.count(start, step))

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, Seq
>>>
>>> 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
>>>
>>> Iter.from_fn(make_counter(5)).collect(Seq)
Seq(1, 2, 3, 4, 5)
Stateful callable class:
>>> from pyochain import Iter, Some, NONE
>>> from dataclasses import dataclass
>>> @dataclass
... class Counter:
...     max: int
...     count: int = 0
...
...     def __call__(self) -> Option[int]:
...         self.count += 1
...         return Some(self.count) if self.count <= self.max else NONE
>>>
>>> Iter.from_fn(Counter(5)).collect(Seq)
Seq(1, 2, 3, 4, 5)
Simulated file/queue reader:
>>> from pyochain import Iter, Some, NONE
>>> from pyochain.collections import Deque
>>>
>>> def queue_consumer(items: Deque[int]) -> Callable[[], Option[int]]:
...     def consume() -> Option[int]:
...         return Some(items.pop_left()) if items else NONE
...
...     return consume
>>>
>>> Iter.from_fn(Deque([1, 2, 3]).pipe(queue_consumer)).collect(Seq)
Seq(1, 2, 3)

Source code in src/pyochain/abc/_iterator.py
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
@classmethod
def from_fn[**P, R](
    cls, f: Callable[P, Option[R]], *args: P.args, **kwargs: P.kwargs
) -> PyoIterator[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, Seq
        >>>
        >>> 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
        >>>
        >>> Iter.from_fn(make_counter(5)).collect(Seq)
        Seq(1, 2, 3, 4, 5)

        ```
        Stateful callable class:
        ```python
        >>> from pyochain import Iter, Some, NONE
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class Counter:
        ...     max: int
        ...     count: int = 0
        ...
        ...     def __call__(self) -> Option[int]:
        ...         self.count += 1
        ...         return Some(self.count) if self.count <= self.max else NONE
        >>>
        >>> Iter.from_fn(Counter(5)).collect(Seq)
        Seq(1, 2, 3, 4, 5)

        ```
        Simulated file/queue reader:
        ```python
        >>> from pyochain import Iter, Some, NONE
        >>> from pyochain.collections import Deque
        >>>
        >>> def queue_consumer(items: Deque[int]) -> Callable[[], Option[int]]:
        ...     def consume() -> Option[int]:
        ...         return Some(items.pop_left()) if items else NONE
        ...
        ...     return consume
        >>>
        >>> Iter.from_fn(Deque([1, 2, 3]).pipe(queue_consumer)).collect(Seq)
        Seq(1, 2, 3)

        ```
    """
    return cls._from_iterable(tls.FromFn(f, *args, **kwargs))

from_repeat(obj, n=None) classmethod

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

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

Be sure to use PyoIterator::take or PyoIterator::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

PyoIterator::cycle to repeat the elements of the Iterator. PyoIterator::repeat to repeat the entire Iterator.

Example

>>> from pyochain import Seq, Iter
>>> Iter.from_repeat(1, 3).collect(Seq)
Seq(1, 1, 1)
>>> Iter.from_repeat(("a", "b"), 2).collect(Seq)
Seq(('a', 'b'), ('a', 'b'))
Shared reference behavior:
>>> from pyochain import Vec
>>>
>>> base = ["Alice", "Bob", "Charlie"]
>>>
>>> first, second = Iter.from_repeat(base).take(2).collect(tuple)
>>> first.append("Joe")
>>> first
['Alice', 'Bob', 'Charlie', 'Joe']
>>> base
['Alice', 'Bob', 'Charlie', 'Joe']
>>> second
['Alice', 'Bob', 'Charlie', 'Joe']
>>> first is second and first is base and second is base
True

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

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

    Be sure to use [`PyoIterator::take`][PyoIterator.take] or [`PyoIterator::slice`][PyoIterator.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:
        [`PyoIterator::cycle`][cycle] to repeat the **elements** of the `Iterator`.
        [`PyoIterator::repeat`][repeat] to repeat the **entire** `Iterator`.

    Example:
        ```python
        >>> from pyochain import Seq, Iter
        >>> Iter.from_repeat(1, 3).collect(Seq)
        Seq(1, 1, 1)
        >>> Iter.from_repeat(("a", "b"), 2).collect(Seq)
        Seq(('a', 'b'), ('a', 'b'))

        ```
        Shared reference behavior:
        ```python
        >>> from pyochain import Vec
        >>>
        >>> base = ["Alice", "Bob", "Charlie"]
        >>>
        >>> first, second = Iter.from_repeat(base).take(2).collect(tuple)
        >>> first.append("Joe")
        >>> first
        ['Alice', 'Bob', 'Charlie', 'Joe']
        >>> base
        ['Alice', 'Bob', 'Charlie', 'Joe']
        >>> second
        ['Alice', 'Bob', 'Charlie', 'Joe']
        >>> first is second and first is base and second is base
        True

        ```
    """
    if n is None:
        return cls._from_iterable(itertools.repeat(obj))
    return cls._from_iterable(itertools.repeat(obj, n))

ge(other)

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

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

The first differing pair decides the result.

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

Note

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

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

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).ge((1, 2))
True
>>> Iter((1, 2, 3)).ge((1, 2, 3))
True
>>> Iter((1, 2)).ge((1, 2, 3))
False
Source code in src/pyochain/abc/_iterator.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def ge(self, other: Iterable[T]) -> bool:
    """Return `True` if **self** is lexicographically greater than or equal to *other*.

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

    The first differing pair decides the result.

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

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

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

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

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

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

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

None

If not specified or is None, key defaults to an identity function and returns the element unchanged.

Returns:

Type Description
PyoIterator[tuple[Any | T, PyoIterator[T]]]

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

Example

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
>>> (
...     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)
... )
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 Iter
>>> data = (
...     {"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 = (
...     Iter(data)
...     .group_by(lambda x: x["gender"])
...     .map_star(lambda g, vals: (g, vals.count()))
...     .collect(Seq)
... )
>>> output
Seq(('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 Iter
>>> groups = (
...     Iter(("a1", "a2", "b1"))
...     .group_by(lambda x: x[0])
...     .collect(Seq)
...     .iter()
...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
...     .collect(Seq)
... )
>>> groups
Seq(('a', Seq()), ('b', Seq()))
As such, the correct pattern is the following:
>>> from pyochain import Iter
>>> groups = (
...     Iter(("a1", "a2", "b1", "b2"))
...     .group_by(lambda x: x[0])
...     # ✅ Materialize NOW
...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
...     .collect(Seq)
... )
>>> groups
Seq(('a', Seq('a1', 'a2')), ('b', Seq('b1', 'b2')))

Source code in src/pyochain/abc/_iterator.py
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
def group_by(
    self,
    key: Callable[[T], Any] | None = None,  # pyright: ignore[reportExplicitAny]
) -> PyoIterator[tuple[Any | T, PyoIterator[T]]]:  # pyright: ignore[reportExplicitAny]
    """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 not specified or is None, **key** defaults to an identity function and returns the element unchanged.

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

    Example:
        `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
        >>> (
        ...     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)
        ... )
        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 Iter
        >>> data = (
        ...     {"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 = (
        ...     Iter(data)
        ...     .group_by(lambda x: x["gender"])
        ...     .map_star(lambda g, vals: (g, vals.count()))
        ...     .collect(Seq)
        ... )
        >>> output
        Seq(('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 Iter
        >>> groups = (
        ...     Iter(("a1", "a2", "b1"))
        ...     .group_by(lambda x: x[0])
        ...     .collect(Seq)
        ...     .iter()
        ...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
        ...     .collect(Seq)
        ... )
        >>> groups
        Seq(('a', Seq()), ('b', Seq()))

        ```
        As such, the correct pattern is the following:
        ```python
        >>> from pyochain import Iter
        >>> groups = (
        ...     Iter(("a1", "a2", "b1", "b2"))
        ...     .group_by(lambda x: x[0])
        ...     # ✅ Materialize NOW
        ...     .map_star(lambda g, vals: (g, vals.collect(Seq)))
        ...     .collect(Seq)
        ... )
        >>> groups
        Seq(('a', Seq('a1', 'a2')), ('b', Seq('b1', 'b2')))

        ```
    """
    new = self._from_iterable
    return new((x, new(y)) for x, y in itertools.groupby(iter(self), key))

gt(other)

Return True if self is lexicographically strictly greater than other.

The first differing pair of elements decides the result.

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

Note

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly after other.

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

    The first differing pair of elements decides the result.

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

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

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

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

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

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

insert(value)

Prepend the value to the Iterator.

Note

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

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

See Also

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

Parameters:

Name Type Description Default
value T

The value to prepend.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: A new Iterable wrapper with the value prepended.

Example
>>> from pyochain import Iter, Seq
>>> Iter((2, 3)).insert(1).collect(Seq)
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
def insert(self, value: T) -> PyoIterator[T]:
    """Prepend the *value* to the `Iterator`.

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

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

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

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

    Returns:
        PyoIterator[T]: A new Iterable wrapper with the value prepended.

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

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

intersperse(element)

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

Parameters:

Name Type Description Default
element T

The element to interpose between items.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: A new Iterator with the element interposed.

Example
>>> from pyochain import Iter, Seq
>>> # Simple example with numbers
>>> Iter((1, 2, 3)).intersperse(0).collect(Seq)
Seq(1, 0, 2, 0, 3)
>>> # Useful when chaining with other operations
>>> Iter([10, 20, 30]).intersperse(5).sum()
70
>>> # Inserting separators between groups, then flattening
>>> Iter(((1, 2), (3, 4), (5, 6))).intersperse([-1]).flatten().collect(Seq)
Seq(1, 2, -1, 3, 4, -1, 5, 6)
Source code in src/pyochain/abc/_iterator.py
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
def intersperse(self, element: T) -> PyoIterator[T]:
    """Creates a new `Iterator` which places a copy of separator between adjacent items of the original iterator.

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

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

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

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

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

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

The elements of the Iterator must support comparison operations.

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

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

Credits to more-itertools for the implementation.

See Also

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

Parameters:

Name Type Description Default
reverse bool

Whether to check for descending order.

False
strict bool

Whether to enforce strict sorting (no equal elements).

False

Returns:

Name Type Description
bool bool

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

Example

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

Source code in src/pyochain/abc/_iterator.py
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
def is_sorted[U: SupportsComparison[Any]](
    self: PyoIterator[U], *, reverse: bool = False, strict: bool = False
) -> bool:
    """Returns `True` if the items of the `Iterator` are in sorted order.

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

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

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

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

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

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

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

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

        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        >>> from pyochain import Seq
        >>> data = Seq((1, 2, 2))
        >>> data.iter().is_sorted()
        True
        >>> data.iter().is_sorted(strict=True)
        False

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

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

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

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

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

Credits to more-itertools for the implementation.

Parameters:

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

Function to extract a comparison key from each element.

required
reverse bool

Whether to check for descending order.

False
strict bool

Whether to enforce strict sorting (no equal elements).

False

Returns:

Name Type Description
bool bool

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

Example

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

Source code in src/pyochain/abc/_iterator.py
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
def is_sorted_by(
    self,
    key: Callable[[T], SupportsComparison[Any]],  # pyright: ignore[reportExplicitAny]
    *,
    reverse: bool = False,
    strict: bool = False,
) -> bool:
    """Returns `True` if the items of the `Iterator` are in sorted order according to the key function.

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

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

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

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

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

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

        ```
        If strict, tests for strict sorting, that is, returns False if equal elements are found:
        ```python
        >>> from pyochain import Seq
        >>> data = Seq(("1", "2", "2"))
        >>> data.iter().is_sorted_by(int)
        True
        >>> data.iter().is_sorted_by(int, strict=True)
        False

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

join(sep)

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

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

Parameters:

Name Type Description Default
sep str

Separator to use between elements.

required

Returns:

Name Type Description
str str

The joined string.

Example
>>> from pyochain import Iter
>>> Iter(("a", "b", "c")).join("-")
'a-b-c'
Source code in src/pyochain/abc/_iterator.py
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
def join(self: PyoIterable[str], sep: str) -> str:
    """Join all elements of the `Iterator` into a single `str`, with a specified separator.

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

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

    Returns:
        str: The joined string.

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

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

le(other)

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

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

The first differing pair decides the result.

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

Note

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

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

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

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

    The first differing pair decides the result.

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

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

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

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

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

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

lt(other)

Return True if self is lexicographically strictly less than other.

The first differing pair of elements decides the result.

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

Note

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True if self compares strictly before other.

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

    The first differing pair of elements decides the result.

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

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

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

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

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

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

map(func)

Apply a function func to each element of the Iterator.

If you are good at thinking in types, you can think of PyoIterator::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.

PyoIterator::map is conceptually similar to a for loop.

However, as PyoIterator::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 PyoIterator.for_each than PyoIterator.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 Iter, Seq
>>> Iter((1, 2)).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"))
>>> data.iter().map(str.upper).collect(Seq)
Seq('A', 'B', 'C')
>>> data.iter().map(lambda s: s.upper()).collect(Seq)
Seq('A', 'B', 'C')
Source code in src/pyochain/abc/_iterator.py
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
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 `PyoIterator::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`.

    `PyoIterator::map` is conceptually similar to a for loop.

    However, as `PyoIterator::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 `PyoIterator.for_each` than `PyoIterator.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 Iter, Seq
        >>> Iter((1, 2)).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"))
        >>> data.iter().map(str.upper).collect(Seq)
        Seq('A', 'B', 'C')
        >>> data.iter().map(lambda s: s.upper()).collect(Seq)
        Seq('A', 'B', 'C')

        ```
    """
    return self._from_iterable(map(func, iter(self)))

map_juxt(*funcs)

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 PyoIterator::{for_each, fold} with mutable collections, or PyoIterator::map followed by PyoIterator::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 iterable of tuples containing the results of each function.

Example

>>> from pyochain import Iter, Seq
>>>
>>> def is_even(n: int) -> bool:
...     return n % 2 == 0
>>> def is_positive(n: int) -> bool:
...     return n > 0
>>>
>>> Iter([1, -2, 3]).map_juxt(is_even, is_positive).collect(Seq)
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:
>>> def curried_add(a: int) -> Callable[[int], int]:
...     def fn(b: int) -> int:
...         return a + b
...
...     return fn
>>>
>>> Iter((1, 2, 3)).map_juxt(curried_add(10), curried_add(20)).collect(Seq)
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:

>>> from pyochain import Range
>>> res = (
...     Range(0, 5)
...     .iter()
...     .map_juxt(lambda x: x * 2, lambda x: x**2)
...     .filter_star(lambda double, square: double + square <= 5)
...     .collect(Seq)
... )
>>> res
Seq((0, 0), (2, 1))

Source code in src/pyochain/abc/_iterator.py
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
def map_juxt(self, *funcs: Callable[[T], Any]) -> PyoIterator[tuple[Any, ...]]:  # pyright: ignore[reportExplicitAny]
    """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 `PyoIterator::{for_each, fold}` with mutable collections, or `PyoIterator::map` followed by `PyoIterator::zip` to combine the results.

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

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

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>>
        >>> def is_even(n: int) -> bool:
        ...     return n % 2 == 0
        >>> def is_positive(n: int) -> bool:
        ...     return n > 0
        >>>
        >>> Iter([1, -2, 3]).map_juxt(is_even, is_positive).collect(Seq)
        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
        >>> def curried_add(a: int) -> Callable[[int], int]:
        ...     def fn(b: int) -> int:
        ...         return a + b
        ...
        ...     return fn
        >>>
        >>> Iter((1, 2, 3)).map_juxt(curried_add(10), curried_add(20)).collect(Seq)
        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
        >>> from pyochain import Range
        >>> res = (
        ...     Range(0, 5)
        ...     .iter()
        ...     .map_juxt(lambda x: x * 2, lambda x: x**2)
        ...     .filter_star(lambda double, square: double + square <= 5)
        ...     .collect(Seq)
        ... )
        >>> res
        Seq((0, 0), (2, 1))

        ```
    """
    return self._from_iterable(map(tls.Juxt(*funcs), iter(self)))

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]

Applies a function to each element.where each element is an iterable.

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

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

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 iterable 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"))
>>> data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
Seq('blue-S', 'blue-M', 'red-S', 'red-M')
>>> # This is equivalent to:
>>> data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
Seq('blue-S', 'blue-M', 'red-S', 'red-M')
Source code in src/pyochain/abc/_iterator.py
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
def map_star[U: AnyIter, R](
    self: PyoIterator[U], func: Callable[..., R]
) -> PyoIterator[R]:
    """Applies a function to each element.where each element is an iterable.

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

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

    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 iterable 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"))
        >>> data.iter().product(["S", "M"]).map_star(make_sku).collect(Seq)
        Seq('blue-S', 'blue-M', 'red-S', 'red-M')
        >>> # This is equivalent to:
        >>> data.iter().product(["S", "M"]).map(lambda x: make_sku(*x)).collect(Seq)
        Seq('blue-S', 'blue-M', 'red-S', 'red-M')

        ```
    """
    return self._from_iterable(itertools.starmap(func, iter(self)))

map_while(func)

Creates an Iterator that both yields elements based on a predicate and maps.

map_while() takes a closure as an argument.

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

After NONE is returned, PyoIterator::map_while stops and the rest of the elements are ignored.

Parameters:

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

Function to apply to each element that returns Option[R].

required

Returns:

Type Description
PyoIterator[R]

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

Example
>>> from pyochain import Iter, Some, NONE, Seq
>>>
>>> def checked_div(x: int) -> Option[int]:
...     return Some(16 // x) if x != 0 else NONE
>>>
>>> data = Iter((-1, 4, 0, 1))
>>> data.map_while(checked_div).collect(Seq)
Seq(-16, 4)
>>> data = Iter((0, 1, 2, -3, 4, 5, -6))
>>> # Convert to positive ints, stop at first negative
>>> data.map_while(lambda x: Some(x) if x >= 0 else NONE).collect(Seq)
Seq(0, 1, 2)
Source code in src/pyochain/abc/_iterator.py
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
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 as an argument.

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

    After `NONE` is returned, `PyoIterator::map_while` stops and the rest of the elements are ignored.

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

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

    Example:
        ```python
        >>> from pyochain import Iter, Some, NONE, Seq
        >>>
        >>> def checked_div(x: int) -> Option[int]:
        ...     return Some(16 // x) if x != 0 else NONE
        >>>
        >>> data = Iter((-1, 4, 0, 1))
        >>> data.map_while(checked_div).collect(Seq)
        Seq(-16, 4)
        >>> data = Iter((0, 1, 2, -3, 4, 5, -6))
        >>> # Convert to positive ints, stop at first negative
        >>> data.map_while(lambda x: Some(x) if x >= 0 else NONE).collect(Seq)
        Seq(0, 1, 2)

        ```
    """
    return self._from_iterable(tls.MapWhile(iter(self), func))

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

PyoIterator::map_windows_star for a version that unpacks the window into separate arguments.

Example
>>> from pyochain import Iter, Seq, Range
>>> import statistics
>>> Iter((1, 2, 3, 4)).map_windows(2, statistics.mean).collect(Seq)
Seq(1.5, 2.5, 3.5)
>>> joined = (
...     Iter("abcd")
...     .map_windows(3, lambda window: "".join(window).upper())
...     .collect(Seq)
... )
>>> joined
Seq('ABC', 'BCD')
>>> sum_windows = Range(0, 5).iter().map_windows(4, sum).collect(Seq)
>>> sum_windows
Seq(6, 10)
Source code in src/pyochain/abc/_iterator.py
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
def map_windows[R](
    self,
    length: int,
    func: Callable[[tuple[Any, ...]], R],  # pyright: ignore[reportExplicitAny]
) -> 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:
        [`PyoIterator::map_windows_star`][map_windows_star] for a version that unpacks the window into separate arguments.

    Example:
        ```python
        >>> from pyochain import Iter, Seq, Range
        >>> import statistics
        >>> Iter((1, 2, 3, 4)).map_windows(2, statistics.mean).collect(Seq)
        Seq(1.5, 2.5, 3.5)
        >>> joined = (
        ...     Iter("abcd")
        ...     .map_windows(3, lambda window: "".join(window).upper())
        ...     .collect(Seq)
        ... )
        >>> joined
        Seq('ABC', 'BCD')
        >>> sum_windows = Range(0, 5).iter().map_windows(4, sum).collect(Seq)
        >>> sum_windows
        Seq(6, 10)

        ```
    """
    return self._from_iterable(map(func, tls.SlidingWindow(iter(self), length)))

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

PyoIterator::map_windows for a version that passes the entire window as a single tuple argument.

Example
>>> from pyochain import Iter, Seq
>>> Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
Seq('a+b', 'b+c', 'c+d')
>>> Iter([1, 2, 3, 4]).map_windows_star(2, lambda x, y: x + y).collect(Seq)
Seq(3, 5, 7)
Source code in src/pyochain/abc/_iterator.py
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
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:
        [`PyoIterator::map_windows`][map_windows] for a version that passes the entire window as a single tuple argument.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter("abcd").map_windows_star(2, lambda x, y: f"{x}+{y}").collect(Seq)
        Seq('a+b', 'b+c', 'c+d')
        >>> Iter([1, 2, 3, 4]).map_windows_star(2, lambda x, y: x + y).collect(Seq)
        Seq(3, 5, 7)

        ```
    """
    return self._from_iterable(
        itertools.starmap(func, tls.SlidingWindow(iter(self), length))
    )

map_with(*iterables, func)

map_with(
    iterable: Iterable[T1], /, *, func: Callable[[T, T1], R]
) -> PyoIterator[R]
map_with(
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    /,
    *,
    func: Callable[[T, T1, T2], R],
) -> PyoIterator[R]
map_with(
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    /,
    *,
    func: Callable[[T, T1, T2, T3], R],
) -> PyoIterator[R]
map_with(
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    /,
    *,
    func: Callable[[T, T1, T2, T3, T4], R],
) -> PyoIterator[R]
map_with(
    iterable: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    iter5: Iterable[T5],
    /,
    *,
    func: Callable[[T, T1, T2, T3, T4, T5], R],
) -> PyoIterator[R]
map_with(
    iterable: AnyIter,
    iter2: AnyIter,
    iter3: AnyIter,
    iter4: AnyIter,
    iter5: AnyIter,
    iter6: AnyIter,
    /,
    *iterables: AnyIter,
    func: Callable[..., R],
) -> 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
*iterables AnyIter

Additional iterables to zip with self.

()
func Callable[..., R]

Function to apply to the elements of the iterables.

required

Returns:

Type Description
PyoIterator[R]

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

See Also

PyoIterator::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(y, z, func=Triangle).collect(Seq)
>>> output
Seq(Triangle(x=1, y=4, z=7), Triangle(x=2, y=5, z=8), Triangle(x=3, y=6, z=9))
Source code in src/pyochain/abc/_iterator.py
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
def map_with[R](
    self, *iterables: AnyIter, func: Callable[..., R]
) -> 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:
        *iterables (AnyIter): Additional iterables to zip with **self**.
        func (Callable[..., R]): Function to apply to the elements of the iterables.

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

    See Also:
        [`PyoIterator::map_juxt`][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(y, z, func=Triangle).collect(Seq)
        >>> output
        Seq(Triangle(x=1, y=4, z=7), Triangle(x=2, y=5, z=8), Triangle(x=3, y=6, z=9))

        ```
    """
    return self._from_iterable(map(func, iter(self), *iterables))

max()

Return the maximum element of the Iterator.

The elements of the Iterator must support comparison operations.

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

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

Returns:

Name Type Description
U U

The maximum value.

Example
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).max()
3
Source code in src/pyochain/abc/_iterator.py
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
def max[U: SupportsAnyRichComparison](self: PyoIterable[U]) -> U:
    """Return the maximum element of the `Iterator`.

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

    For comparing elements using a custom **key** function, use [`max_by`][max_by] instead.

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

    Returns:
        U: The maximum value.

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

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

max_by(key)

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

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

Parameters:

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

Function to extract a comparison key from each element.

required

Returns:

Name Type Description
T T

The element with the maximum key value.

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

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

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

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

    Example:
        ```python
        >>> from pyochain import Seq
        >>> from dataclasses import dataclass
        >>>
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        ...     is_student: bool
        ...
        ...     def get_discount(self) -> float:
        ...         return 0.1 if self.is_student else 0.0
        >>>
        >>> alice = Person("Alice", 30, False)
        >>> bob = Person("Bob", 22, True)
        >>> charlie = Person("Charlie", 25, False)
        >>> persons = Seq((alice, bob, charlie))
        >>>
        >>> persons.iter().max_by(lambda p: p.age).name
        'Alice'
        >>> persons.iter().max_by(lambda p: p.name).name
        'Charlie'
        >>> persons.iter().max_by(Person.get_discount).name
        'Bob'

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

min()

Return the minimum of the Iterator.

The elements of the Iterator must support comparison operations.

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

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

Returns:

Name Type Description
U U

The minimum value.

Example
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).min()
1
Source code in src/pyochain/abc/_iterator.py
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
def min[U: SupportsAnyRichComparison](self: PyoIterable[U]) -> U:
    """Return the minimum of the `Iterator`.

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

    For comparing elements using a custom **key** function, use [`min_by`][min_by] instead.

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

    Returns:
        U: The minimum value.

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

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

min_by(key)

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

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

Parameters:

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

Function to extract a comparison key from each element.

required

Returns:

Name Type Description
T T

The element with the minimum key value.

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

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

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

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

    Example:
        ```python
        >>> from pyochain import Seq
        >>> from dataclasses import dataclass
        >>>
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        ...     is_student: bool
        ...
        ...     def get_discount(self) -> float:
        ...         return 0.1 if self.is_student else 0.0
        >>>
        >>> alice = Person("Alice", 30, False)
        >>> bob = Person("Bob", 22, True)
        >>> charlie = Person("Charlie", 25, False)
        >>> persons = Seq((alice, bob, charlie))
        >>>
        >>> persons.iter().min_by(lambda p: p.age).name
        'Bob'
        >>> persons.iter().min_by(lambda p: p.name).name
        'Alice'
        >>> persons.iter().min_by(Person.get_discount).name
        'Alice'

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

ne(other)

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

This is the logical opposite of eq().

The result becomes True as soon as:

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

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

Parameters:

Name Type Description Default
other Iterable[T]

Another Iterable[T] to compare against.

required

Returns:

Name Type Description
bool bool

True when the two iterables are not equal.

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

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

    The result becomes `True` as soon as:

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

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

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

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

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

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

next()

Return the next element in the Iterator.

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

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

Returns:

Type Description
Option[T]

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

Example
>>> from pyochain import Seq
>>> it = Seq((1, 2, 3)).iter()
>>> it.next().unwrap()
1
>>> it.next().unwrap()
2
Source code in src/pyochain/abc/_iterator.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
def next(self) -> Option[T]:
    """Return the next element in the `Iterator`.

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

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

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

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

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

nth(n)

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

This is similar to __getitem__ but for lazy Iterators.

If n is out of bounds, returns NONE.

Parameters:

Name Type Description Default
n int

The index of the item to retrieve.

required

Returns:

Type Description
Option[T]

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

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

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

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

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

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

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

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

once(value) classmethod

Create an Iterator that yields a single value.

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 equivalent of .insert() but as a 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
>>> Iter.once(42).collect(Seq)
Seq(42,)
Source code in src/pyochain/abc/_iterator.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@classmethod
def once[V](cls, value: V) -> PyoIterator[V]:
    """Create an `Iterator` that yields a single value.

    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 equivalent of `.insert()` but as a 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
        >>> Iter.once(42).collect(Seq)
        Seq(42,)

        ```
    """
    return cls._from_iterable((value,))

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 equivalent of PyoIterator::insert but as a constructor.

Unlike PyoIterator::once, this function will lazily generate the value on request.

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
>>> Iter.once_with(lambda: 42).collect(Seq)
Seq(42,)
Source code in src/pyochain/abc/_iterator.py
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
@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 equivalent of [`PyoIterator::insert`][PyoIterator.insert] but as a constructor.

    Unlike `PyoIterator::once`, this function will lazily generate the value on request.

    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
        >>> Iter.once_with(lambda: 42).collect(Seq)
        Seq(42,)

        ```
    """

    def _once_with() -> Generator[R]:
        yield func(*args, **kwargs)

    return cls._from_iterable(_once_with())

pairwise()

Return an iterator over pairs of consecutive elements.

Returns:

Type Description
PyoIterator[tuple[T, T]]

PyoIterator[tuple[T, T]]: An iterable of pairs of consecutive elements.

Example
>>> from pyochain import Seq
>>> Seq((1, 2, 3)).iter().pairwise().collect(Seq)
Seq((1, 2), (2, 3))
Source code in src/pyochain/abc/_iterator.py
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
def pairwise(self) -> PyoIterator[tuple[T, T]]:
    """Return an iterator over pairs of consecutive elements.

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

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

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

partition(predicate)

Consumes the Iterator, creating two Vec from it.

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

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

Parameters:

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

Function to determine partition boundaries.

required

Returns:

Type Description
tuple[Vec[T], Vec[T]]

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

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3, 4, 5)).partition(lambda x: x % 2 == 0)
(Vec(2, 4), Vec(1, 3, 5))
Source code in src/pyochain/abc/_iterator.py
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
def partition(self, predicate: Callable[[T], bool]) -> tuple[Vec[T], Vec[T]]:
    """Consumes the `Iterator`, creating two `Vec` from it.

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

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

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

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

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3, 4, 5)).partition(lambda x: x % 2 == 0)
        (Vec(2, 4), Vec(1, 3, 5))

        ```
    """
    from .._vec import Vec

    first, second = tls.partition(iter(self), predicate)
    return Vec.from_ref(first), Vec.from_ref(second)

peekable(n)

Retrieve the next n elements from the Iterator, whilst leaving the original iterator unconsumed.

The returned tuple contains two elements:

  • A Seq of the next n elements.
  • An Iterator that includes the peeked elements followed by the remaining elements of the original Iterator.

Parameters:

Name Type Description Default
n int

Number of items to peek.

required

Returns:

Type Description
tuple[Seq[T], PyoIterator[T]]

tuple[Seq[T], PyoIterator[T]]: A tuple containing the peeked elements and the remaining iterator.

See Also

[Iter::cloned][cloned] to create an independent copy of the iterator.

Example
>>> from pyochain import Iter, Seq
>>> peeked, remaining = Iter((1, 2, 3)).peekable(2)
>>> peeked
Seq(1, 2)
>>> remaining.collect(Seq)
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
def peekable(self, n: int) -> tuple[Seq[T], PyoIterator[T]]:
    """Retrieve the next **n** elements from the `Iterator`, whilst leaving the original iterator unconsumed.

    The returned tuple contains two elements:

    - A `Seq` of the next **n** elements.
    - An `Iterator` that includes the peeked elements followed by the remaining elements of the original `Iterator`.

    Args:
        n (int): Number of items to peek.

    Returns:
        tuple[Seq[T], PyoIterator[T]]: A tuple containing the peeked elements and the remaining iterator.

    See Also:
        [`Iter::cloned`][cloned] to create an independent copy of the iterator.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> peeked, remaining = Iter((1, 2, 3)).peekable(2)
        >>> peeked
        Seq(1, 2)
        >>> remaining.collect(Seq)
        Seq(1, 2, 3)

        ```
    """
    from .._seq import Seq

    iterator = iter(self)
    peeked = Seq(itertools.islice(iterator, n))
    remaining = self._from_iterable(itertools.chain(peeked, iterator))
    return peeked, remaining

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 all permutations of length r.

Parameters:

Name Type Description Default
r int | None

Length of each permutation. Defaults to the length of the iterable.

None

Returns:

Type Description
PyoIterator[tuple[T, ...]]

PyoIterator[tuple[T, ...]]: An iterable of permutations.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).permutations(2).collect(Seq)
Seq((1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2))
Source code in src/pyochain/abc/_iterator.py
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
def permutations(self, r: int | None = None) -> PyoIterator[tuple[T, ...]]:
    """Return all permutations of length r.

    Args:
        r (int | None): Length of each permutation. Defaults to the length of the iterable.

    Returns:
        PyoIterator[tuple[T, ...]]: An iterable of permutations.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 3)).permutations(2).collect(Seq)
        Seq((1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2))

        ```
    """
    return self._from_iterable(itertools.permutations(iter(self), r))

product(*others)

product() -> PyoIterator[tuple[T]]
product(iter1: Iterable[T1]) -> PyoIterator[tuple[T, T1]]
product(
    iter1: Iterable[T1], iter2: Iterable[T2]
) -> PyoIterator[tuple[T, T1, T2]]
product(
    iter1: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
) -> PyoIterator[tuple[T, T1, T2, T3]]
product(
    iter1: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
) -> PyoIterator[tuple[T, T1, T2, T3, T4]]

Computes the Cartesian product with another iterable.

This is the declarative equivalent of nested for-loops.

It pairs every element from the source iterable with every element from the other iterable.

Parameters:

Name Type Description Default
*others AnyIter

Other iterables to compute the Cartesian product with.

()

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
>>>
>>> data = Seq(("blue", "red"))
>>> data.iter().product(["S", "M"]).collect(Seq)
Seq(('blue', 'S'), ('blue', 'M'), ('red', 'S'), ('red', 'M'))
>>> res = (
...     data
...     .iter()
...     .product(["S", "M"])
...     .map_star(lambda color, size: f"{color}-{size}")
...     .collect(Seq)
... )
>>> res
Seq('blue-S', 'blue-M', 'red-S', 'red-M')
>>> res = (
...     Range(1, 4)
...     .iter()
...     .product([10, 20])
...     .filter_star(lambda a, b: a * b >= 40)
...     .map_star(lambda a, b: a * b)
...     .collect(Seq)
... )
>>> res
Seq(40, 60)
>>> res = (
...     Iter
...     .once(1)
...     .product(["a", "b"], [True])
...     .filter_star(lambda _a, b, _c: b != "a")
...     .map_star(lambda a, b, c: f"{a}{b} is {c}")
...     .collect(Seq)
... )
>>> res
Seq('1b is True',)
Source code in src/pyochain/abc/_iterator.py
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
def product(self, *others: AnyIter) -> PyoIterator[tuple[Any, ...]]:  # pyright: ignore[reportExplicitAny]
    """Computes the Cartesian product with another iterable.

    This is the declarative equivalent of nested for-loops.

    It pairs every element from the source iterable with every element from the
    other iterable.

    Args:
        *others (AnyIter): Other iterables to compute the Cartesian product with.

    Returns:
        PyoIterator[tuple[Any, ...]]: An iterable of tuples containing elements from the Cartesian product.

    Example:
        ```python
        >>> from pyochain import Seq, Range, Iter
        >>>
        >>> data = Seq(("blue", "red"))
        >>> data.iter().product(["S", "M"]).collect(Seq)
        Seq(('blue', 'S'), ('blue', 'M'), ('red', 'S'), ('red', 'M'))
        >>> res = (
        ...     data
        ...     .iter()
        ...     .product(["S", "M"])
        ...     .map_star(lambda color, size: f"{color}-{size}")
        ...     .collect(Seq)
        ... )
        >>> res
        Seq('blue-S', 'blue-M', 'red-S', 'red-M')
        >>> res = (
        ...     Range(1, 4)
        ...     .iter()
        ...     .product([10, 20])
        ...     .filter_star(lambda a, b: a * b >= 40)
        ...     .map_star(lambda a, b: a * b)
        ...     .collect(Seq)
        ... )
        >>> res
        Seq(40, 60)
        >>> res = (
        ...     Iter
        ...     .once(1)
        ...     .product(["a", "b"], [True])
        ...     .filter_star(lambda _a, b, _c: b != "a")
        ...     .map_star(lambda a, b, c: f"{a}{b} is {c}")
        ...     .collect(Seq)
        ... )
        >>> res
        Seq('1b is True',)

        ```
    """
    return self._from_iterable(itertools.product(iter(self), *others))

reduce(func)

Apply a function of two arguments cumulatively to the items of an iterable, from left to right.

This effectively reduces the Iterator to a single value.

If initial is present, it is placed before the items of the Iterator in the calculation.

It then serves as a default when the Iterator is empty.

Parameters:

Name Type Description Default
func Callable[[T, T], T]

Function to apply cumulatively to the items of the iterable.

required

Returns:

Name Type Description
T T

Single value resulting from cumulative reduction.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).reduce(lambda a, b: a + b)
6
Source code in src/pyochain/abc/_iterator.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def reduce(self, func: Callable[[T, T], T]) -> T:
    """Apply a function of two arguments cumulatively to the items of an iterable, from left to right.

    This effectively reduces the `Iterator` to a single value.

    If initial is present, it is placed before the items of the `Iterator` in the calculation.

    It then serves as a default when the `Iterator` is empty.

    Args:
        func (Callable[[T, T], T]): Function to apply cumulatively to the items of the iterable.

    Returns:
        T: Single value resulting from cumulative reduction.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).reduce(lambda a, b: a + b)
        6

        ```
    """
    return functools.reduce(func, iter(self))

repeat(n=None)

Repeat the entire Iterator n times (as elements).

If n is None, repeat indefinitely.

Operates lazily, hence if you need to get the underlying elements, you will need to collect each repeated Iterator via .map(lambda x: x.collect(Seq)) or similar.

Warning

If n is None, this will create an infinite Iterator.

Be sure to use PyoIterator::take or PyoIterator::slice to limit the number of items taken.

See Also

PyoIterator::cycle to repeat the elements of the PyoIterator indefinitely.

Parameters:

Name Type Description Default
n int | None

Optional number of repetitions.

None

Returns:

Type Description
PyoIterator[PyoIterator[T]]

PyoIterator[PyoIterator[T]]: An Iterator of repeated Iterators.

Example
>>> from pyochain import Iter, Seq
>>>
>>> Iter((1, 2)).repeat(3).map(list).collect(Seq)
Seq([1, 2], [1, 2], [1, 2])
Source code in src/pyochain/abc/_iterator.py
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
def repeat(self, n: int | None = None) -> PyoIterator[PyoIterator[T]]:
    """Repeat the entire `Iterator` **n** times (as elements).

    If **n** is `None`, repeat indefinitely.

    Operates lazily, hence if you need to get the underlying elements, you will need to collect each repeated `Iterator` via `.map(lambda x: x.collect(Seq))` or similar.

    Warning:
        If **n** is `None`, this will create an infinite `Iterator`.

        Be sure to use `PyoIterator::take` or `PyoIterator::slice` to limit the number of items taken.

    See Also:
        [`PyoIterator::cycle`][cycle] to repeat the *elements* of the `PyoIterator` indefinitely.

    Args:
        n (int | None): Optional number of repetitions.

    Returns:
        PyoIterator[PyoIterator[T]]: An `Iterator` of repeated `Iterator`s.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>>
        >>> Iter((1, 2)).repeat(3).map(list).collect(Seq)
        Seq([1, 2], [1, 2], [1, 2])

        ```
    """
    new = self._from_iterable

    def _repeat_infinite() -> Generator[PyoIterator[T]]:
        tee = functools.partial(itertools.tee, iter(self), 1)
        iterators = tee()
        while True:
            yield new(iterators[0])
            iterators = tee()

    match n:
        case None:
            return new(_repeat_infinite())
        case _:
            return new(map(new, itertools.tee(iter(self), n)))

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
>>>
>>> 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
>>> Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
Seq(1, 3, 6, 10)
Source code in src/pyochain/abc/_iterator.py
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
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
        >>>
        >>> 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
        >>> Range(1, 6).iter().scan(0, accumulate_until_limit).collect(Seq)
        Seq(1, 3, 6, 10)

        ```
    """
    return self._from_iterable(tls.Scan(iter(self), initial, func))

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))
>>> data.iter().skip(1).collect(Seq)
Seq(2, 3)
>>> data.iter().skip(5).collect(Seq)
Seq()
>>> data.iter().skip(0).collect(Seq)
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
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))
        >>> data.iter().skip(1).collect(Seq)
        Seq(2, 3)
        >>> data.iter().skip(5).collect(Seq)
        Seq()
        >>> data.iter().skip(0).collect(Seq)
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), n, None))

skip_while(predicate)

Drop items while predicate holds.

Parameters:

Name Type Description Default
predicate Callable[[T], bool]

Function to evaluate each item.

required

Returns:

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)
>>> out
Seq(0, -1)
Source code in src/pyochain/abc/_iterator.py
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
def skip_while(self, predicate: Callable[[T], bool]) -> PyoIterator[T]:
    """Drop items while predicate holds.

    Args:
        predicate (Callable[[T], bool]): 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)
        >>> out
        Seq(0, -1)

        ```
    """
    return self._from_iterable(itertools.dropwhile(predicate, iter(self)))

slice(start=None, stop=None, step=None)

Return a slice of the Iterator.

Parameters:

Name Type Description Default
start int | None

Starting index of the slice.

None
stop int | None

Ending index of the slice.

None
step int | None

Step size for the slice.

None

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the sliced items.

Example
>>> from pyochain import Seq
>>> data = Seq((1, 2, 3, 4, 5))
>>> data.iter().slice(1, 4).collect(Seq)
Seq(2, 3, 4)
>>> data.iter().slice(step=2).collect(Seq)
Seq(1, 3, 5)
Source code in src/pyochain/abc/_iterator.py
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
def slice(
    self,
    start: int | None = None,
    stop: int | None = None,
    step: int | None = None,
) -> PyoIterator[T]:
    """Return a slice of the `Iterator`.

    Args:
        start (int | None): Starting index of the slice.
        stop (int | None): Ending index of the slice.
        step (int | None): Step size for the slice.

    Returns:
        PyoIterator[T]: An `Iterator` of the sliced items.

    Example:
        ```python
        >>> from pyochain import Seq
        >>> data = Seq((1, 2, 3, 4, 5))
        >>> data.iter().slice(1, 4).collect(Seq)
        Seq(2, 3, 4)
        >>> data.iter().slice(step=2).collect(Seq)
        Seq(1, 3, 5)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), start, stop, step))

sort(*, reverse=False)

Sort the elements of the Iterator.

The elements must support rich comparison operations (i.e., they must implement the necessary comparison dunder methods).

Note

This method must consume the entire Iterator to perform the sort.

The result is a new Vec over the sorted sequence.

Parameters:

Name Type Description Default
reverse bool

Whether to sort in descending order.

False

Returns:

Type Description
Vec[U]

Vec[U]: A Vec with elements sorted.

Example
>>> from pyochain import Iter
>>> Iter((3, 1, 2)).sort()
Vec(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
def sort[U: SupportsAnyRichComparison](
    self: PyoIterator[U], *, reverse: bool = False
) -> Vec[U]:
    """Sort the elements of the `Iterator`.

    The elements must support rich comparison operations (i.e., they must implement the necessary comparison dunder methods).

    Note:
        This method must consume the entire `Iterator` to perform the sort.

        The result is a new `Vec` over the sorted sequence.

    Args:
        reverse (bool): Whether to sort in descending order.

    Returns:
        Vec[U]: A `Vec` with elements sorted.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((3, 1, 2)).sort()
        Vec(1, 2, 3)

        ```
    """
    from .._vec import Vec

    return Vec.from_ref(sorted(iter(self), reverse=reverse))

sort_by(key, *, reverse=False)

Sort the elements of the sequence transformed by the key function.

Note

This method must consume the entire Iterator to perform the sort.

The result is a new Vec over the sorted sequence.

Parameters:

Name Type Description Default
key Callable[[T], SupportsAnyRichComparison]

Function to extract a comparison key from each element.

required
reverse bool

Whether to sort in descending order.

False

Returns:

Type Description
Vec[T]

Vec[T]: A Vec with elements sorted.

Example
>>> from pyochain import Seq
>>> str_numbers = Seq(("3", "1", "2"))
>>> str_numbers.iter().sort_by(int)
Vec('1', '2', '3')
>>> 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)
... )
>>> sorted_names
Seq('Bob', 'Alice', 'Charlie')
Source code in src/pyochain/abc/_iterator.py
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
def sort_by(
    self, key: Callable[[T], SupportsAnyRichComparison], *, reverse: bool = False
) -> Vec[T]:
    """Sort the elements of the sequence transformed by the key function.

    Note:
        This method must consume the entire `Iterator` to perform the sort.

        The result is a new `Vec` over the sorted sequence.

    Args:
        key (Callable[[T], SupportsAnyRichComparison]): Function to extract a comparison key from each element.
        reverse (bool): Whether to sort in descending order.

    Returns:
        Vec[T]: A `Vec` with elements sorted.

    Example:
        ```python
        >>> from pyochain import Seq
        >>> str_numbers = Seq(("3", "1", "2"))
        >>> str_numbers.iter().sort_by(int)
        Vec('1', '2', '3')
        >>> 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)
        ... )
        >>> sorted_names
        Seq('Bob', 'Alice', 'Charlie')

        ```
    """
    from .._vec import Vec

    return Vec.from_ref(sorted(iter(self), reverse=reverse, key=key))

step_by(step)

Creates an Iterator starting at the same point, but stepping by the given step at each iteration.

Note

The first element of the iterator will always be returned, regardless of the step given.

Parameters:

Name Type Description Default
step int

Step size for selecting items.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of every nth item.

Example
>>> from pyochain import Seq
>>> Seq((0, 1, 2, 3, 4, 5)).iter().step_by(2).collect(Seq)
Seq(0, 2, 4)
Source code in src/pyochain/abc/_iterator.py
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
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
        >>> Seq((0, 1, 2, 3, 4, 5)).iter().step_by(2).collect(Seq)
        Seq(0, 2, 4)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), 0, None, step))

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
>>>
>>> Iter.successors(Some(1), next_pow10).collect(Seq)
Seq(1, 10, 100, 1000, 10000)
>>> Iter.successors(NONE, next_pow10).collect(Seq)
Seq()
Source code in src/pyochain/abc/_iterator.py
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
@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
        >>>
        >>> Iter.successors(Some(1), next_pow10).collect(Seq)
        Seq(1, 10, 100, 1000, 10000)
        >>> Iter.successors(NONE, next_pow10).collect(Seq)
        Seq()

        ```
    """
    return cls._from_iterable(tls.Successors(first, succ))

sum(start=0)

sum(start: int = 0) -> int
sum(start: int = 0) -> int
sum() -> T1 | Literal[0]
sum(start: A2) -> A1 | A2

Return the sum of the Iterator.

If the Iterator is empty (i.e., yields no elements), return the value of start (which defaults to 0).

Parameters:

Name Type Description Default
start int | T1 | A2

The value to return if the Iterator is empty.

0

Returns:

Type Description
int | T1 | A1 | A2

int | T1 | A1 | A2: The sum of all elements.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 3)).sum()
6
>>> Iter(()).sum()
0
>>> Iter(()).sum(10)
10
Source code in src/pyochain/abc/_iterator.py
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
def sum[T1: SupportsSumWithNoDefaultGiven, A1: SupportsAnyAdd, A2: SupportsAnyAdd](
    self: PyoIterator[bool | LiteralInteger] | PyoIterator[T1] | PyoIterator[A1],
    start: int | T1 | A2 = 0,
) -> int | T1 | A1 | A2:
    """Return the sum of the `Iterator`.

    If the `Iterator` is empty (i.e., yields no elements), return the value of `start` (which defaults to `0`).

    Args:
        start (int | T1 | A2): The value to return if the `Iterator` is empty.

    Returns:
        int | T1 | A1 | A2: The sum of all elements.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 3)).sum()
        6
        >>> Iter(()).sum()
        0
        >>> Iter(()).sum(10)
        10

        ```
    """
    return sum(iter(self), start)

tail(n)

Return a Deque of the last n elements of the Iterator.

Parameters:

Name Type Description Default
n int

Number of elements to return.

required

Returns:

Type Description
Deque[T]

Deque[T]: A Deque containing the last n elements.

Example
>>> from pyochain import Iter
>>> Iter((1, 2, 3)).tail(2)
Deque([2, 3], maxlen=2)
Source code in src/pyochain/abc/_iterator.py
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
def tail(self, n: int) -> Deque[T]:
    """Return a `Deque` of the last **n** elements of the `Iterator`.

    Args:
        n (int): Number of elements to return.

    Returns:
        Deque[T]: A `Deque` containing the last **n** elements.

    Example:
        ```python
        >>> from pyochain import Iter
        >>> Iter((1, 2, 3)).tail(2)
        Deque([2, 3], maxlen=2)

        ```
    """
    from collections import deque

    from ..collections import Deque

    # TODO: we should move this to Rust and make it fully lazy.
    return Deque.from_ref(deque(iter(self), n))

take(n)

Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner.

Iter.take(n) yields elements until n elements are yielded or the end of the iterator is reached (whichever happens first).

The returned iterator is either:

  • A prefix of length n if the original iterator contains at least n elements
  • All of the (fewer than n) elements of the original iterator if it contains fewer than n elements.

Parameters:

Name Type Description Default
n int

Number of elements to take.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the first n items.

Example
>>> from pyochain import Seq
>>> data = Seq((1, 2, 3))
>>> data.iter().take(2).collect(Seq)
Seq(1, 2)
>>> data.iter().take(5).collect(Seq)
Seq(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
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))
        >>> data.iter().take(2).collect(Seq)
        Seq(1, 2)
        >>> data.iter().take(5).collect(Seq)
        Seq(1, 2, 3)

        ```
    """
    return self._from_iterable(itertools.islice(iter(self), n))

take_while(predicate)

Take items while predicate holds.

Parameters:

Name Type Description Default
predicate Callable[[T], bool]

Function to evaluate each item.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the items taken while the predicate is true.

Example
>>> from pyochain import Iter, Seq
>>> Iter((1, 2, 0)).take_while(lambda x: x > 0).collect(Seq)
Seq(1, 2)
Source code in src/pyochain/abc/_iterator.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
def take_while(self, predicate: Callable[[T], bool]) -> PyoIterator[T]:
    """Take items while predicate holds.

    Args:
        predicate (Callable[[T], bool]): Function to evaluate each item.

    Returns:
        PyoIterator[T]: An `Iterator` of the items taken while the predicate is true.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> Iter((1, 2, 0)).take_while(lambda x: x > 0).collect(Seq)
        Seq(1, 2)

        ```
    """
    return self._from_iterable(itertools.takewhile(predicate, iter(self)))

try_collect()

try_collect() -> Option[Vec[U]]
try_collect() -> Option[Vec[U]]

Fallibly transforms self into a Vec, short circuiting if a failure is encountered.

try_collect() is a variation of collect() that allows fallible conversions during collection.

Its main use case is simplifying conversions from iterators yielding Option[T] or Result[T, E] into Option[Vec[T]].

Also, if a failure is encountered during try_collect(), the 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 Iter, Some, Ok, Err, NONE, Vec
>>> # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
>>> Iter((Some(1), Some(2), Some(3))).try_collect()
Some(Vec(1, 2, 3))
>>> # Failing to collect in the same way:
>>> Iter((Some(1), Some(2), NONE, Some(3))).try_collect()
NONE
>>> # A similar example, but with Result:
>>> Iter((Ok(1), Ok(2), Ok(3))).try_collect()
Some(Vec(1, 2, 3))
>>> Iter((Ok(1), Err("error"), Ok(3))).try_collect()
NONE
>>> def external_fn(x: int) -> Option[int]:
...     if x % 2 == 0:
...         return Some(x)
...     return NONE
>>>
>>> Iter((1, 2, 3, 4)).map(external_fn).try_collect()
NONE
>>> # Demonstrating that the iterator remains usable after a failure:
>>> it = Iter((Some(1), NONE, Some(3), Some(4)))
>>> it.try_collect()
NONE
>>> it.try_collect()
Some(Vec(3, 4))
Source code in src/pyochain/abc/_iterator.py
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
def try_collect[U](
    self: PyoIterator[Option[U]] | PyoIterator[Result[U, Any]],  # pyright: ignore[reportExplicitAny]
) -> Option[Vec[U]]:
    """Fallibly transforms **self** into a `Vec`, short circuiting if a failure is encountered.

    `try_collect()` is a variation of `collect()` that allows fallible conversions during collection.

    Its main use case is simplifying conversions from iterators yielding `Option[T]` or `Result[T, E]` into `Option[Vec[T]]`.

    Also, if a failure is encountered during `try_collect()`, the `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 Iter, Some, Ok, Err, NONE, Vec
        >>> # Successfully collecting an iterator of Option[int] into Option[Vec[int]]:
        >>> Iter((Some(1), Some(2), Some(3))).try_collect()
        Some(Vec(1, 2, 3))
        >>> # Failing to collect in the same way:
        >>> Iter((Some(1), Some(2), NONE, Some(3))).try_collect()
        NONE
        >>> # A similar example, but with Result:
        >>> Iter((Ok(1), Ok(2), Ok(3))).try_collect()
        Some(Vec(1, 2, 3))
        >>> Iter((Ok(1), Err("error"), Ok(3))).try_collect()
        NONE
        >>> def external_fn(x: int) -> Option[int]:
        ...     if x % 2 == 0:
        ...         return Some(x)
        ...     return NONE
        >>>
        >>> Iter((1, 2, 3, 4)).map(external_fn).try_collect()
        NONE
        >>> # Demonstrating that the iterator remains usable after a failure:
        >>> it = Iter((Some(1), NONE, Some(3), Some(4)))
        >>> it.try_collect()
        NONE
        >>> it.try_collect()
        Some(Vec(3, 4))

        ```
    """
    from .._vec import Vec

    return tls.try_collect(iter(self)).map(Vec.from_ref)

try_find(predicate)

Applies a function returning Result[bool, E] to find first matching element.

Short-circuits: stops at the first successful True or on the first error.

Parameters:

Name Type Description Default
predicate Callable[[T], Result[bool, E]]

Function returning a Result[bool, E].

required

Returns:

Type Description
Result[Option[T], E]

Result[Option[T], E]: The first matching element, or the first error.

Example
>>> from pyochain import Ok, Result, Err, Range
>>>
>>> def is_even(x: int) -> Result[bool, str]:
...     return Ok(x % 2 == 0) if x >= 0 else Err("negative number")
>>>
>>> Range(1, 6).iter().try_find(is_even)
Ok(Some(2))
Source code in src/pyochain/abc/_iterator.py
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
def try_find[E](
    self, predicate: Callable[[T], Result[bool, E]]
) -> Result[Option[T], E]:
    """Applies a function returning `Result[bool, E]` to find first matching element.

    Short-circuits: stops at the first successful `True` or on the first error.

    Args:
        predicate (Callable[[T], Result[bool, E]]): Function returning a `Result[bool, E]`.

    Returns:
        Result[Option[T], E]: The first matching element, or the first error.

    Example:
        ```python
        >>> from pyochain import Ok, Result, Err, Range
        >>>
        >>> def is_even(x: int) -> Result[bool, str]:
        ...     return Ok(x % 2 == 0) if x >= 0 else Err("negative number")
        >>>
        >>> Range(1, 6).iter().try_find(is_even)
        Ok(Some(2))

        ```
    """
    return tls.try_find(iter(self), predicate)

try_fold(init, func)

Folds every element into an accumulator, short-circuiting on error.

Applies func cumulatively to items and the accumulator.

If func returns an error, stops and returns that error.

Parameters:

Name Type Description Default
init B

Initial accumulator value.

required
func Callable[[B, T], Result[B, E]]

Function that takes the accumulator and element, returns a Result[B, E].

required

Returns:

Type Description
Result[B, E]

Result[B, E]: Final accumulator or the first error.

Example
>>> from pyochain import Iter, Ok, Err, Result
>>>
>>> def checked_add(acc: int, x: int) -> Result[int, str]:
...     new_val = acc + x
...     if new_val > 100:
...         return Err("overflow")
...     return Ok(new_val)
>>>
>>> Iter((1, 2, 3)).try_fold(0, checked_add)
Ok(6)
>>> Iter([50, 40, 20]).try_fold(0, checked_add)
Err('overflow')
>>> Iter(()).try_fold(0, checked_add)
Ok(0)
Source code in src/pyochain/abc/_iterator.py
 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
def try_fold[B, E](
    self, init: B, func: Callable[[B, T], Result[B, E]]
) -> Result[B, E]:
    """Folds every element into an accumulator, short-circuiting on error.

    Applies **func** cumulatively to items and the accumulator.

    If **func** returns an error, stops and returns that error.

    Args:
        init (B): Initial accumulator value.
        func (Callable[[B, T], Result[B, E]]): Function that takes the accumulator and element, returns a `Result[B, E]`.

    Returns:
        Result[B, E]: Final accumulator or the first error.

    Example:
        ```python
        >>> from pyochain import Iter, Ok, Err, Result
        >>>
        >>> def checked_add(acc: int, x: int) -> Result[int, str]:
        ...     new_val = acc + x
        ...     if new_val > 100:
        ...         return Err("overflow")
        ...     return Ok(new_val)
        >>>
        >>> Iter((1, 2, 3)).try_fold(0, checked_add)
        Ok(6)
        >>> Iter([50, 40, 20]).try_fold(0, checked_add)
        Err('overflow')
        >>> Iter(()).try_fold(0, checked_add)
        Ok(0)

        ```
    """
    return tls.try_fold(iter(self), init, func)

try_for_each(f)

Applies a fallible function to each item in the Iterator, stopping at the first error and returning that error.

This can also be thought of as the fallible form of .for_each().

Parameters:

Name Type Description Default
f Callable[[T], Result[Any, E]]

A function that takes an item of type T and returns a Result.

required

Returns:

Type Description
Result[tuple[], E]

Result[tuple[()], E]: Returns Ok(()) if all applications of f were successful (i.e., returned Ok), or the first error E encountered.

Example
>>> from pyochain import Iter, Result, Ok, Err
>>> def validate_positive(n: int) -> Result[tuple[()], str]:
...     if n > 0:
...         return Ok("success")
...     return Err(f"Value {n} is not positive")
>>>
>>> Iter((1, 2, 3, 4, 5)).try_for_each(validate_positive)
Ok(())
>>> # Short-circuit on first error:
>>> Iter((1, 2, -1, 4)).try_for_each(validate_positive)
Err('Value -1 is not positive')
Source code in src/pyochain/abc/_iterator.py
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
def try_for_each[E](self, f: Callable[[T], Result[Any, E]]) -> Result[tuple[()], E]:  # pyright: ignore[reportExplicitAny]
    """Applies a fallible function to each item in the `Iterator`, stopping at the first error and returning that error.

    This can also be thought of as the fallible form of `.for_each()`.

    Args:
        f (Callable[[T], Result[Any, E]]): A function that takes an item of type `T` and returns a `Result`.

    Returns:
        Result[tuple[()], E]: Returns `Ok(())` if all applications of **f** were successful (i.e., returned `Ok`), or the first error `E` encountered.

    Example:
        ```python
        >>> from pyochain import Iter, Result, Ok, Err
        >>> def validate_positive(n: int) -> Result[tuple[()], str]:
        ...     if n > 0:
        ...         return Ok("success")
        ...     return Err(f"Value {n} is not positive")
        >>>
        >>> Iter((1, 2, 3, 4, 5)).try_for_each(validate_positive)
        Ok(())
        >>> # Short-circuit on first error:
        >>> Iter((1, 2, -1, 4)).try_for_each(validate_positive)
        Err('Value -1 is not positive')

        ```
    """
    return tls.try_for_each(iter(self), f)

try_reduce(func)

Reduces elements to a single one, short-circuiting on error.

Uses the first element as the initial accumulator. If func returns an error, stops immediately.

Parameters:

Name Type Description Default
func Callable[[T, T], Result[T, E]]

Function that reduces two items, returns a Result[T, E].

required

Returns:

Type Description
Result[Option[T], E]

Result[Option[T], E]: Final accumulated value or the first error. Returns Ok(NONE) for empty iterable.

Example
>>> from pyochain import Iter, Ok, Err, Result
>>>
>>> def checked_add(x: int, y: int) -> Result[int, str]:
...     if x + y > 100:
...         return Err("overflow")
...     return Ok(x + y)
>>>
>>> Iter((1, 2, 3)).try_reduce(checked_add)
Ok(Some(6))
>>> Iter([50, 60]).try_reduce(checked_add)
Err('overflow')
>>> Iter(()).try_reduce(checked_add)
Ok(NONE)
Source code in src/pyochain/abc/_iterator.py
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
def try_reduce[E](
    self, func: Callable[[T, T], Result[T, E]]
) -> Result[Option[T], E]:
    """Reduces elements to a single one, short-circuiting on error.

    Uses the first element as the initial accumulator. If **func** returns an error, stops immediately.

    Args:
        func (Callable[[T, T], Result[T, E]]): Function that reduces two items, returns a `Result[T, E]`.

    Returns:
        Result[Option[T], E]: Final accumulated value or the first error. Returns `Ok(NONE)` for empty iterable.

    Example:
        ```python
        >>> from pyochain import Iter, Ok, Err, Result
        >>>
        >>> def checked_add(x: int, y: int) -> Result[int, str]:
        ...     if x + y > 100:
        ...         return Err("overflow")
        ...     return Ok(x + y)
        >>>
        >>> Iter((1, 2, 3)).try_reduce(checked_add)
        Ok(Some(6))
        >>> Iter([50, 60]).try_reduce(checked_add)
        Err('overflow')
        >>> Iter(()).try_reduce(checked_add)
        Ok(NONE)

        ```
    """
    return tls.try_reduce(iter(self), func)

unique()

Return only unique elements of the 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 Seq, Set
>>> data = Seq((1, 1, 2, 2, 3, 3))
>>> data.iter().unique().collect(Seq)
Seq(1, 2, 3)
>>> data.pipe(Set).iter().sort()
Vec(1, 2, 3)
Source code in src/pyochain/abc/_iterator.py
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
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 Seq, Set
        >>> data = Seq((1, 1, 2, 2, 3, 3))
        >>> data.iter().unique().collect(Seq)
        Seq(1, 2, 3)
        >>> data.pipe(Set).iter().sort()
        Vec(1, 2, 3)

        ```
    """
    return self._from_iterable(tls.UniqueIdentity(iter(self)))

unique_by(key)

Return only unique elements of the iterable.

Parameters:

Name Type Description Default
key Callable[[T], Any]

Function to transform items before comparison.

required

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator of the unique items.

Example
>>> from pyochain import Seq
>>> data = Seq(("cat", "mouse", "dog", "hen"))
>>> data.iter().unique_by(key=len).collect(Seq)
Seq('cat', 'mouse')
Source code in src/pyochain/abc/_iterator.py
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
def unique_by(self, key: Callable[[T], Any]) -> PyoIterator[T]:  # pyright: ignore[reportExplicitAny]
    """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"))
        >>> data.iter().unique_by(key=len).collect(Seq)
        Seq('cat', 'mouse')

        ```
    """
    return self._from_iterable(tls.UniqueKey(iter(self), key=key))

unpack_into(func, *args, **kwargs)

Unpack the Iterator in the provided func, and return the result.

This is similar to 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))
>>> data.iter().unpack_into(foo, x="Result: ")
'Result: 6'
>>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
>>> data.iter().unpack_into(lambda a, b, c: a + b + c)
6
Source code in src/pyochain/abc/_iterator.py
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
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))
        >>> data.iter().unpack_into(foo, x="Result: ")
        'Result: 6'
        >>> # The example below will work, but is not type safe, as the unpacked elements are passed as explicit positional arguments.
        >>> data.iter().unpack_into(lambda a, b, c: a + b + c)
        6

        ```
    """
    return func(*iter(self), *args, **kwargs)

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 Iter, Seq
>>> data = ((1, "a"), (2, "b"), (3, "c"))
>>> left, right = Iter(data).unzip()
>>> left.collect(Seq)
Seq(1, 2, 3)
>>> right.collect(Seq)
Seq('a', 'b', 'c')
Source code in src/pyochain/abc/_iterator.py
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
def unzip[U, V](
    self: PyoIterator[tuple[U, V]],
) -> tuple[PyoIterator[U], PyoIterator[V]]:
    """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:
        tuple[PyoIterator[U], PyoIterator[V]]: A tuple containing two iterators, one for each element of the pairs.

    Example:
        ```python
        >>> from pyochain import Iter, Seq
        >>> data = ((1, "a"), (2, "b"), (3, "c"))
        >>> left, right = Iter(data).unzip()
        >>> left.collect(Seq)
        Seq(1, 2, 3)
        >>> right.collect(Seq)
        Seq('a', 'b', 'c')

        ```
    """
    left, right = itertools.tee(iter(self), 2)
    return self._from_iterable(x[0] for x in left), self._from_iterable(
        x[1] for x in right
    )

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"))
>>> data.iter().with_position().collect(Seq)
Seq(('first', 'a'), ('middle', 'b'), ('middle', 'c'), ('last', 'd'))
>>> data.iter().take(1).with_position().collect(Seq)
Seq(('only', 'a'),)
>>> data.iter().take(2).with_position().collect(Seq)
Seq(('first', 'a'), ('last', 'b'))
Source code in src/pyochain/abc/_iterator.py
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
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"))
        >>> data.iter().with_position().collect(Seq)
        Seq(('first', 'a'), ('middle', 'b'), ('middle', 'c'), ('last', 'd'))
        >>> data.iter().take(1).with_position().collect(Seq)
        Seq(('only', 'a'),)
        >>> data.iter().take(2).with_position().collect(Seq)
        Seq(('first', 'a'), ('last', 'b'))

        ```
    """
    return self._from_iterable(tls.WithPosition(iter(self)))

zip(*others, strict=False)

zip(
    iter1: Iterable[T1], /, *, strict: bool = ...
) -> PyoIterator[tuple[T, T1]]
zip(
    iter1: Iterable[T1],
    iter2: Iterable[T2],
    /,
    *,
    strict: bool = ...,
) -> PyoIterator[tuple[T, T1, T2]]
zip(
    iter1: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    /,
    *,
    strict: bool = ...,
) -> PyoIterator[tuple[T, T1, T2, T3]]
zip(
    iter1: Iterable[T1],
    iter2: Iterable[T2],
    iter3: Iterable[T3],
    iter4: Iterable[T4],
    /,
    *,
    strict: bool = ...,
) -> PyoIterator[tuple[T, T1, T2, T3, T4]]

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

Iter.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 AnyIter

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 Iter, Seq
>>>
>>> Iter((1, 2)).zip((10, 20)).collect(Seq)
Seq((1, 10), (2, 20))
>>> Iter(("a", "b")).zip((1, 2, 3)).collect(Seq)
Seq(('a', 1), ('b', 2))
Source code in src/pyochain/abc/_iterator.py
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
def zip(
    self, *others: AnyIter, strict: bool = False
) -> PyoIterator[tuple[Any, ...]]:  # pyright: ignore[reportExplicitAny]
    """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:
        `Iter.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 (AnyIter): 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 Iter, Seq
        >>>
        >>> Iter((1, 2)).zip((10, 20)).collect(Seq)
        Seq((1, 10), (2, 20))
        >>> Iter(("a", "b")).zip((1, 2, 3)).collect(Seq)
        Seq(('a', 1), ('b', 2))

        ```
    """
    return self._from_iterable(zip(iter(self), *others, strict=strict))

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],
    ]
]
zip_longest(
    iter2: Iterable[T],
    iter3: Iterable[T],
    iter4: Iterable[T],
    iter5: Iterable[T],
    iter6: Iterable[T],
    /,
    *iterables: AnyIter,
) -> PyoIterator[tuple[Option[T], ...]]

Return a zip Iterator who yield a tuple where the i-th element comes from the i-th iterable argument.

Yield values until the longest iterable in the argument sequence is exhausted, and then it raises StopIteration.

The longest iterable determines the length of the returned iterator, and will return Some[T] until exhaustion.

When the shorter iterables are exhausted, they yield NONE.

Parameters:

Name Type Description Default
*others AnyIter

Other iterables to zip with.

()

Returns:

Type Description
ZippedLongest[T]

ZippedLongest[T]: An iterable of tuples containing optional elements from the zipped iterables.

Example
>>> from pyochain import Iter, Some, NONE, Vec
>>> Iter((1, 2)).zip_longest([10]).collect(Vec)
Vec((Some(1), Some(10)), (Some(2), NONE))
>>> # Can be combined with try collect to filter out the NONE:
>>> zipped = (
...     Iter((1, 2))
...     .zip_longest([10])
...     .map(lambda x: Iter(x).try_collect())
...     .collect(Vec)
... )
>>> zipped
Vec(Some(Vec(1, 10)), NONE)
Source code in src/pyochain/abc/_iterator.py
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
def zip_longest(self, *others: AnyIter) -> ZippedLongest[T]:
    """Return a zip Iterator who yield a tuple where the i-th element comes from the i-th iterable argument.

    Yield values until the longest iterable in the argument sequence is exhausted, and then it raises StopIteration.

    The longest iterable determines the length of the returned iterator, and will return `Some[T]` until exhaustion.

    When the shorter iterables are exhausted, they yield `NONE`.

    Args:
        *others (AnyIter): Other iterables to zip with.

    Returns:
        ZippedLongest[T]: An iterable of tuples containing optional elements from the zipped iterables.

    Example:
        ```python
        >>> from pyochain import Iter, Some, NONE, Vec
        >>> Iter((1, 2)).zip_longest([10]).collect(Vec)
        Vec((Some(1), Some(10)), (Some(2), NONE))
        >>> # Can be combined with try collect to filter out the NONE:
        >>> zipped = (
        ...     Iter((1, 2))
        ...     .zip_longest([10])
        ...     .map(lambda x: Iter(x).try_collect())
        ...     .collect(Vec)
        ... )
        >>> zipped
        Vec(Some(Vec(1, 10)), NONE)

        ```
    """
    return self._from_iterable(
        tuple(option(t) for t in tup)
        for tup in itertools.zip_longest(iter(self), *others, fillvalue=None)
    )