pyiter.stream

   1from __future__ import annotations
   2
   3if __name__ == "__main__":
   4    from pathlib import Path
   5
   6    __package__ = Path(__file__).parent.name
   7
   8from typing import (
   9    overload,
  10    Any,
  11    List,
  12    Set,
  13    Dict,
  14    Generic,
  15    Iterable,
  16    Iterator,
  17    Union,
  18    Optional,
  19    Tuple,
  20    Type,
  21    Callable,
  22    Literal,
  23    NamedTuple,
  24    Awaitable,
  25    TYPE_CHECKING,
  26)
  27
  28if TYPE_CHECKING:
  29    from _typeshed import SupportsRichComparisonT
  30    from random import Random
  31    from .parallel_mapping import ParallelMappingTransform
  32    from .grouping import Grouping
  33    from .list_like import ListLike
  34
  35# from typing_extensions import deprecated
  36from functools import cached_property
  37import sys
  38
  39
  40if sys.version_info < (3, 11):
  41    # Generic NamedTuple
  42    origin__namedtuple_mro_entries = NamedTuple.__mro_entries__  # type: ignore
  43    NamedTuple.__mro_entries__ = lambda bases: origin__namedtuple_mro_entries(bases[:1])  # type: ignore
  44
  45from .transform import Transform, NonTransform, new_transform, T, U, K, O as V
  46from .error import LazyEvaluationException
  47
  48
  49class Stream(Generic[T], Iterable[T]):
  50    """
  51    Given an [iterator] function constructs a [Stream] that returns values through the [Iterator]
  52    provided by that function.
  53
  54    The values are evaluated lazily, and the sequence is potentially infinite.
  55    """
  56
  57    __transform__: Transform[Any, T]
  58
  59    def __init__(self, iterable: Union[Iterable[T], Transform[Any, T]]) -> None:
  60        super().__init__()
  61
  62        self.__transform__ = new_transform(iterable)
  63
  64    @cached_property
  65    def transforms(self) -> Iterable[Transform[Any, Any]]:
  66        return [*self.__transform__.transforms()]
  67
  68    @property
  69    def data(self) -> List[T]:
  70        if self.__transform__.cache is not None:
  71            return self.__transform__.cache.copy()
  72        if is_debugging():
  73            raise LazyEvaluationException("The sequence has not been evaluated yet.")
  74        return self.to_list()
  75
  76    def dedup(self) -> Stream[T]:
  77        """
  78        Removes consecutive repeated elements in the sequence.
  79
  80        If the sequence is sorted, this removes all duplicates.
  81
  82        Example 1:
  83        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
  84        >>> it(lst).dedup().to_list()
  85        ['a1', 'b2', 'a2', 'a1']
  86
  87        Example 1:
  88        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
  89        >>> it(lst).sorted().dedup().to_list()
  90        ['a1', 'a2', 'b2']
  91        """
  92        return self.dedup_by(lambda x: x)
  93
  94    @overload
  95    def dedup_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ...
  96    @overload
  97    def dedup_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ...
  98    @overload
  99    def dedup_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ...
 100    def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
 101        """
 102        Removes all but the first of consecutive elements in the sequence that resolve to the same key.
 103        """
 104        return self.dedup_into_group_by(key_selector).map(lambda x: x[0])
 105
 106    @overload
 107    def dedup_with_count_by(self, key_selector: Callable[[T], Any]) -> Stream[Tuple[T, int]]: ...
 108    @overload
 109    def dedup_with_count_by(
 110        self, key_selector: Callable[[T, int], Any]
 111    ) -> Stream[Tuple[T, int]]: ...
 112    @overload
 113    def dedup_with_count_by(
 114        self, key_selector: Callable[[T, int, Stream[T]], Any]
 115    ) -> Stream[Tuple[T, int]]: ...
 116    def dedup_with_count_by(self, key_selector: Callable[..., Any]) -> Stream[Tuple[T, int]]:
 117        """
 118        Removes all but the first of consecutive elements and its count that resolve to the same key.
 119
 120        Example 1:
 121        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
 122        >>> it(lst).dedup_with_count_by(lambda x: x).to_list()
 123        [('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)]
 124
 125        Example 1:
 126        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
 127        >>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list()
 128        [('a1', 3), ('a2', 1), ('b2', 1)]
 129        """
 130        return self.dedup_into_group_by(key_selector).map(lambda x: (x[0], len(x)))
 131
 132    @overload
 133    def dedup_into_group_by(self, key_selector: Callable[[T], Any]) -> Stream[List[T]]: ...
 134    @overload
 135    def dedup_into_group_by(self, key_selector: Callable[[T, int], Any]) -> Stream[List[T]]: ...
 136    @overload
 137    def dedup_into_group_by(
 138        self, key_selector: Callable[[T, int, Stream[T]], Any]
 139    ) -> Stream[List[T]]: ...
 140    def dedup_into_group_by(self, key_selector: Callable[..., Any]) -> Stream[List[T]]:
 141        from .dedup import DedupTransform
 142
 143        return it(DedupTransform(self, key_selector))
 144
 145    @overload
 146    def filter(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
 147    @overload
 148    def filter(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
 149    @overload
 150    def filter(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
 151    def filter(self, predicate: Callable[..., bool]) -> Stream[T]:
 152        """
 153        Returns a Stream containing only elements matching the given [predicate].
 154
 155        Example 1:
 156        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 157        >>> it(lst).filter(lambda x: x.startswith('a')).to_list()
 158        ['a1', 'a2']
 159
 160        Example 2:
 161        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 162        >>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list()
 163        ['a1', 'b2', 'a2']
 164        """
 165        from .filtering import FilteringTransform
 166
 167        return it(FilteringTransform(self, self.__callback_overload_warpper__(predicate)))
 168
 169    def filter_is_instance(self, typ: Type[U]) -> Stream[U]:
 170        """
 171        Returns a Stream containing all elements that are instances of specified type parameter typ.
 172
 173        Example 1:
 174        >>> lst = [ 'a1', 1, 'b2', 3]
 175        >>> it(lst).filter_is_instance(int).to_list()
 176        [1, 3]
 177
 178        """
 179        from .type_guard import TypeGuardTransform, TypeGuard
 180
 181        def guard(x: T) -> TypeGuard[U]:
 182            return isinstance(x, typ)
 183
 184        return it(TypeGuardTransform(self, guard))
 185
 186    @overload
 187    def filter_not(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
 188    @overload
 189    def filter_not(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
 190    @overload
 191    def filter_not(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
 192    def filter_not(self, predicate: Callable[..., bool]) -> Stream[T]:
 193        """
 194        Returns a Stream containing all elements not matching the given [predicate].
 195
 196        Example 1:
 197        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 198        >>> it(lst).filter_not(lambda x: x.startswith('a')).to_list()
 199        ['b1', 'b2']
 200
 201        Example 2:
 202        >>> lst = [ 'a1', 'a2', 'b1', 'b2']
 203        >>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list()
 204        ['a2', 'b1', 'b2']
 205        """
 206        predicate = self.__callback_overload_warpper__(predicate)
 207        return self.filter(lambda x: not predicate(x))
 208
 209    @overload
 210    def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]: ...
 211    @overload
 212    def filter_not_none(self: Stream[T]) -> Stream[T]: ...
 213    def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]:
 214        """
 215        Returns a Stream containing all elements that are not `None`.
 216
 217        Example 1:
 218        >>> lst = [ 'a', None, 'b']
 219        >>> it(lst).filter_not_none().to_list()
 220        ['a', 'b']
 221        """
 222        from .type_guard import TypeGuardTransform, TypeGuard
 223
 224        def guard(x: Optional[U]) -> TypeGuard[U]:
 225            return x is not None
 226
 227        return it(TypeGuardTransform(self, guard))
 228
 229    @overload
 230    def map(self, transform: Callable[[T], U]) -> Stream[U]: ...
 231    @overload
 232    def map(self, transform: Callable[[T], U], return_exceptions: Literal[False]) -> Stream[U]: ...
 233    @overload
 234    def map(
 235        self, transform: Callable[[T], U], return_exceptions: Literal[True]
 236    ) -> Stream[Union[U, BaseException]]: ...
 237    @overload
 238    def map(self, transform: Callable[[T, int], U]) -> Stream[U]: ...
 239    @overload
 240    def map(
 241        self, transform: Callable[[T, int], U], return_exceptions: Literal[False]
 242    ) -> Stream[U]: ...
 243    @overload
 244    def map(
 245        self, transform: Callable[[T, int], U], return_exceptions: Literal[True]
 246    ) -> Stream[Union[U, BaseException]]: ...
 247    @overload
 248    def map(self, transform: Callable[[T, int, Stream[T]], U]) -> Stream[U]: ...
 249    @overload
 250    def map(
 251        self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[False]
 252    ) -> Stream[U]: ...
 253    @overload
 254    def map(
 255        self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[True]
 256    ) -> Stream[Union[U, BaseException]]: ...
 257    def map(
 258        self, transform: Callable[..., U], return_exceptions: bool = False
 259    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
 260        """
 261        Returns a Stream containing the results of applying the given [transform] function
 262        to each element in the original Stream.
 263
 264        Example 1:
 265        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 266        >>> it(lst).map(lambda x: x['age']).to_list()
 267        [12, 13]
 268
 269        Example 2:
 270        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 271        >>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list()
 272        ['A0', 'B1']
 273
 274        Example 3:
 275        >>> lst = ['hi', 'abc']
 276        >>> it(lst).map(len).to_list()
 277        [2, 3]
 278        """
 279        from .mapping import MappingTransform
 280
 281        transform = self.__callback_overload_warpper__(transform)
 282        if return_exceptions:
 283
 284            def transform_wrapper(x: T) -> Union[U, BaseException]:
 285                try:
 286                    return transform(x)
 287                except BaseException as e:
 288                    return e
 289
 290            return it(MappingTransform(self, transform_wrapper))
 291
 292        return it(MappingTransform(self, transform))
 293
 294    @overload
 295    async def map_async(self, transform: Callable[[T], Awaitable[U]]) -> Stream[U]: ...
 296    @overload
 297    async def map_async(
 298        self,
 299        transform: Callable[[T, int], Awaitable[U]],
 300        return_exceptions: Literal[True],
 301    ) -> Stream[Union[U, BaseException]]: ...
 302    @overload
 303    async def map_async(
 304        self,
 305        transform: Callable[[T, int, Stream[T]], Awaitable[U]],
 306        return_exceptions: Literal[False] = False,
 307    ) -> Stream[U]: ...
 308    async def map_async(
 309        self, transform: Callable[..., Awaitable[U]], return_exceptions: bool = False
 310    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
 311        """
 312        Similar to `.map()` but you can input a async transform then await it.
 313        """
 314        from asyncio import gather
 315
 316        if return_exceptions:
 317            return it(await gather(*self.map(transform), return_exceptions=True))
 318        return it(await gather(*self.map(transform)))
 319
 320    @overload
 321    def map_not_none(self, transform: Callable[[T], Optional[U]]) -> Stream[U]: ...
 322    @overload
 323    def map_not_none(self, transform: Callable[[T, int], Optional[U]]) -> Stream[U]: ...
 324    @overload
 325    def map_not_none(self, transform: Callable[[T, int, Stream[T]], Optional[U]]) -> Stream[U]: ...
 326    def map_not_none(self, transform: Callable[..., Optional[U]]) -> Stream[U]:
 327        """
 328        Returns a Stream containing only the non-none results of applying the given [transform] function
 329        to each element in the original collection.
 330
 331        Example 1:
 332        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}]
 333        >>> it(lst).map_not_none(lambda x: x['age']).to_list()
 334        [12]
 335        """
 336        return self.map(transform).filter_not_none()  # type: ignore
 337
 338    @overload
 339    def parallel_map(
 340        self,
 341        transform: Callable[[T], U],
 342        max_workers: Optional[int] = None,
 343        chunksize: int = 1,
 344        executor: ParallelMappingTransform.Executor = "Thread",
 345    ) -> Stream[U]: ...
 346    @overload
 347    def parallel_map(
 348        self,
 349        transform: Callable[[T, int], U],
 350        max_workers: Optional[int] = None,
 351        chunksize: int = 1,
 352        executor: ParallelMappingTransform.Executor = "Thread",
 353    ) -> Stream[U]: ...
 354    @overload
 355    def parallel_map(
 356        self,
 357        transform: Callable[[T, int, Stream[T]], U],
 358        max_workers: Optional[int] = None,
 359        chunksize: int = 1,
 360        executor: ParallelMappingTransform.Executor = "Thread",
 361    ) -> Stream[U]: ...
 362    def parallel_map(
 363        self,
 364        transform: Callable[..., U],
 365        max_workers: Optional[int] = None,
 366        chunksize: int = 1,
 367        executor: ParallelMappingTransform.Executor = "Thread",
 368    ) -> Stream[U]:
 369        """
 370        Returns a Stream containing the results of applying the given [transform] function
 371        to each element in the original Stream.
 372
 373        Example 1:
 374        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 375        >>> it(lst).parallel_map(lambda x: x['age']).to_list()
 376        [12, 13]
 377
 378        Example 2:
 379        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 380        >>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list()
 381        [12, 13]
 382
 383        Example 3:
 384        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 385        >>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list()
 386        [12, 14]
 387        """
 388        from .parallel_mapping import ParallelMappingTransform
 389
 390        return it(
 391            ParallelMappingTransform(
 392                self,
 393                self.__callback_overload_warpper__(transform),
 394                max_workers,
 395                chunksize,
 396                executor,
 397            )
 398        )
 399
 400    @overload
 401    def find(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 402    @overload
 403    def find(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 404    @overload
 405    def find(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 406    def find(self, predicate: Callable[..., bool]) -> Optional[T]:
 407        """
 408        Returns the first element matching the given [predicate], or `None` if no such element was found.
 409
 410        Example 1:
 411        >>> lst = ['a', 'b', 'c']
 412        >>> it(lst).find(lambda x: x == 'b')
 413        'b'
 414        """
 415        return self.first_or_none(predicate)
 416
 417    def find_last(self, predicate: Callable[[T], bool]) -> Optional[T]:
 418        """
 419        Returns the last element matching the given [predicate], or `None` if no such element was found.
 420
 421        Example 1:
 422        >>> lst = ['a', 'b', 'c']
 423        >>> it(lst).find_last(lambda x: x == 'b')
 424        'b'
 425        """
 426        return self.last_or_none(predicate)
 427
 428    @overload
 429    def first(self) -> T: ...
 430    @overload
 431    def first(self, predicate: Callable[[T], bool]) -> T: ...
 432    @overload
 433    def first(self, predicate: Callable[[T, int], bool]) -> T: ...
 434    @overload
 435    def first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
 436    def first(self, predicate: Optional[Callable[..., bool]] = None) -> T:
 437        """
 438        Returns first element.
 439
 440        Example 1:
 441        >>> lst = ['a', 'b', 'c']
 442        >>> it(lst).first()
 443        'a'
 444
 445        Example 2:
 446        >>> lst = []
 447        >>> it(lst).first()
 448        Traceback (most recent call last):
 449        ...
 450        ValueError: Stream is empty.
 451
 452        Example 3:
 453        >>> lst = ['a', 'b', 'c']
 454        >>> it(lst).first(lambda x: x == 'b')
 455        'b'
 456
 457        Example 4:
 458        >>> lst = ['a', 'b', 'c']
 459        >>> it(lst).first(lambda x: x == 'd')
 460        Traceback (most recent call last):
 461        ...
 462        ValueError: Stream is empty.
 463
 464        Example 5:
 465        >>> lst = [None]
 466        >>> it(lst).first() is None
 467        True
 468        """
 469        for e in self:
 470            if predicate is None or predicate(e):
 471                return e
 472        raise ValueError("Stream is empty.")
 473
 474    @overload
 475    def first_not_none_of(self: Stream[Optional[U]]) -> U: ...
 476    @overload
 477    def first_not_none_of(
 478        self: Stream[Optional[U]], transform: Callable[[Optional[U]], Optional[U]]
 479    ) -> U: ...
 480    @overload
 481    def first_not_none_of(
 482        self: Stream[Optional[U]],
 483        transform: Callable[[Optional[U], int], Optional[U]],
 484    ) -> U: ...
 485    @overload
 486    def first_not_none_of(
 487        self: Stream[Optional[U]],
 488        transform: Callable[[Optional[U], int, Stream[Optional[U]]], Optional[U]],
 489    ) -> U: ...
 490    def first_not_none_of(
 491        self: Stream[Optional[U]],
 492        transform: Optional[Callable[..., Optional[U]]] = None,
 493    ) -> U:
 494        """
 495        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
 496
 497        Example 1:
 498        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
 499        >>> it(lst).first_not_none_of(lambda x: x['age'])
 500        12
 501
 502        Example 2:
 503        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
 504        >>> it(lst).first_not_none_of(lambda x: x['age'])
 505        Traceback (most recent call last):
 506        ...
 507        ValueError: No element of the Stream was transformed to a non-none value.
 508        """
 509
 510        v = (
 511            self.first_not_none_of_or_none()
 512            if transform is None
 513            else self.first_not_none_of_or_none(transform)
 514        )
 515        if v is None:
 516            raise ValueError("No element of the Stream was transformed to a non-none value.")
 517        return v
 518
 519    @overload
 520    def first_not_none_of_or_none(self) -> Optional[T]: ...
 521    @overload
 522    def first_not_none_of_or_none(self, transform: Callable[[T], T]) -> Optional[T]: ...
 523    @overload
 524    def first_not_none_of_or_none(self, transform: Callable[[T, int], T]) -> Optional[T]: ...
 525    @overload
 526    def first_not_none_of_or_none(
 527        self, transform: Callable[[T, int, Stream[T]], T]
 528    ) -> Optional[T]: ...
 529    def first_not_none_of_or_none(
 530        self, transform: Optional[Callable[..., T]] = None
 531    ) -> Optional[T]:
 532        """
 533        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
 534
 535        Example 1:
 536        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
 537        >>> it(lst).first_not_none_of_or_none(lambda x: x['age'])
 538        12
 539
 540        Example 2:
 541        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
 542        >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None
 543        True
 544        """
 545        if transform is None:
 546            return self.first_or_none()
 547        return self.map_not_none(transform).first_or_none()
 548
 549    @overload
 550    def first_or_none(self) -> Optional[T]: ...
 551    @overload
 552    def first_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 553    @overload
 554    def first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 555    @overload
 556    def first_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 557    def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
 558        """
 559        Returns the first element, or `None` if the Stream is empty.
 560
 561        Example 1:
 562        >>> lst = []
 563        >>> it(lst).first_or_none() is None
 564        True
 565
 566        Example 2:
 567        >>> lst = ['a', 'b', 'c']
 568        >>> it(lst).first_or_none()
 569        'a'
 570
 571        Example 2:
 572        >>> lst = ['a', 'b', 'c']
 573        >>> it(lst).first_or_none(lambda x: x == 'b')
 574        'b'
 575        """
 576        if predicate is not None:
 577            return self.first_or_default(predicate, None)
 578        else:
 579            return self.first_or_default(None)
 580
 581    @overload
 582    def first_or_default(self, default: U) -> Union[T, U]: ...
 583    @overload
 584    def first_or_default(self, predicate: Callable[[T], bool], default: U) -> Union[T, U]: ...
 585    @overload
 586    def first_or_default(self, predicate: Callable[[T, int], bool], default: U) -> Union[T, U]: ...
 587    @overload
 588    def first_or_default(
 589        self, predicate: Callable[[T, int, Stream[T]], bool], default: U
 590    ) -> Union[T, U]: ...
 591    def first_or_default(  # type: ignore
 592        self, predicate: Union[Callable[..., bool], U], default: Optional[U] = None
 593    ) -> Union[T, U, None]:
 594        """
 595        Returns the first element, or the given [default] if the Stream is empty.
 596
 597        Example 1:
 598        >>> lst = []
 599        >>> it(lst).first_or_default('a')
 600        'a'
 601
 602        Example 2:
 603        >>> lst = ['b']
 604        >>> it(lst).first_or_default('a')
 605        'b'
 606
 607        Example 3:
 608        >>> lst = ['a', 'b', 'c']
 609        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
 610        'b'
 611
 612        Example 4:
 613        >>> lst = []
 614        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
 615        'd'
 616        """
 617        seq = self
 618        if isinstance(predicate, Callable):
 619            seq = self.filter(predicate)  # type: ignore
 620        else:
 621            default = predicate
 622        return next(iter(seq), default)
 623
 624    @overload
 625    def last(self) -> T: ...
 626    @overload
 627    def last(self, predicate: Callable[[T], bool]) -> T: ...
 628    @overload
 629    def last(self, predicate: Callable[[T, int], bool]) -> T: ...
 630    @overload
 631    def last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
 632    def last(self, predicate: Optional[Callable[..., bool]] = None) -> T:
 633        """
 634        Returns last element.
 635
 636        Example 1:
 637        >>> lst = ['a', 'b', 'c']
 638        >>> it(lst).last()
 639        'c'
 640
 641        Example 2:
 642        >>> lst = []
 643        >>> it(lst).last()
 644        Traceback (most recent call last):
 645        ...
 646        ValueError: Stream is empty.
 647        """
 648        v = self.last_or_none(predicate) if predicate is not None else self.last_or_none()
 649        if v is None:
 650            raise ValueError("Stream is empty.")
 651        return v
 652
 653    @overload
 654    def last_or_none(self) -> Optional[T]: ...
 655    @overload
 656    def last_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 657    @overload
 658    def last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 659    @overload
 660    def last_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 661    def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
 662        """
 663        Returns the last element matching the given [predicate], or `None` if no such element was found.
 664
 665        Exmaple 1:
 666        >>> lst = ['a', 'b', 'c']
 667        >>> it(lst).last_or_none()
 668        'c'
 669
 670        Exmaple 2:
 671        >>> lst = ['a', 'b', 'c']
 672        >>> it(lst).last_or_none(lambda x: x != 'c')
 673        'b'
 674
 675        Exmaple 3:
 676        >>> lst = []
 677        >>> it(lst).last_or_none(lambda x: x != 'c') is None
 678        True
 679        """
 680        last: Optional[T] = None
 681        for i in self if predicate is None else self.filter(predicate):
 682            last = i
 683        return last
 684
 685    def index_of_or_none(self, element: T) -> Optional[int]:
 686        """
 687        Returns first index of [element], or None if the collection does not contain element.
 688
 689        Example 1:
 690        >>> lst = ['a', 'b', 'c']
 691        >>> it(lst).index_of_or_none('b')
 692        1
 693
 694        Example 2:
 695        >>> lst = ['a', 'b', 'c']
 696        >>> it(lst).index_of_or_none('d')
 697        """
 698        for i, x in enumerate(self):
 699            if x == element:
 700                return i
 701        return None
 702
 703    def index_of(self, element: T) -> int:
 704        """
 705        Returns first index of [element], or -1 if the collection does not contain element.
 706
 707        Example 1:
 708        >>> lst = ['a', 'b', 'c']
 709        >>> it(lst).index_of('b')
 710        1
 711
 712        Example 2:
 713        >>> lst = ['a', 'b', 'c']
 714        >>> it(lst).index_of('d')
 715        -1
 716        """
 717        return none_or(self.index_of_or_none(element), -1)
 718
 719    def index_of_or(self, element: T, default: int) -> int:
 720        """
 721        Returns first index of [element], or default value if the collection does not contain element.
 722
 723        Example 1:
 724        >>> lst = ['a', 'b', 'c']
 725        >>> it(lst).index_of_or('b', 1)
 726        1
 727
 728        Example 2:
 729        >>> lst = ['a', 'b', 'c']
 730        >>> it(lst).index_of_or('d', 0)
 731        0
 732        """
 733        return none_or(self.index_of_or_none(element), default)
 734
 735    def index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
 736        """
 737        Returns first index of [element], or computes the value from a callback if the collection does not contain element.
 738
 739        Example 1:
 740        >>> lst = ['a', 'b', 'c']
 741        >>> it(lst).index_of_or_else('b', lambda: 2)
 742        1
 743
 744        Example 2:
 745        >>> lst = ['a', 'b', 'c']
 746        >>> it(lst).index_of_or_else('d', lambda: 0)
 747        0
 748        """
 749        return none_or_else(self.index_of_or_none(element), f)
 750
 751    def last_index_of_or_none(self, element: T) -> Optional[int]:
 752        """
 753         Returns last index of [element], or None if the collection does not contain element.
 754
 755        Example 1:
 756        >>> lst = ['a', 'b', 'c', 'b']
 757        >>> it(lst).last_index_of_or_none('b')
 758        3
 759
 760        Example 2:
 761        >>> lst = ['a', 'b', 'c']
 762        >>> it(lst).last_index_of_or_none('d')
 763        """
 764        seq = self.reversed()
 765        last_idx = len(seq) - 1
 766        for i, x in enumerate(seq):
 767            if x == element:
 768                return last_idx - i
 769        return None
 770
 771    def last_index_of(self, element: T) -> int:
 772        """
 773         Returns last index of [element], or -1 if the collection does not contain element.
 774
 775        Example 1:
 776        >>> lst = ['a', 'b', 'c', 'b']
 777        >>> it(lst).last_index_of('b')
 778        3
 779
 780        Example 2:
 781        >>> lst = ['a', 'b', 'c']
 782        >>> it(lst).last_index_of('d')
 783        -1
 784        """
 785        return none_or(self.last_index_of_or_none(element), -1)
 786
 787    def last_index_of_or(self, element: T, default: int) -> int:
 788        """
 789         Returns last index of [element], or default value if the collection does not contain element.
 790
 791        Example 1:
 792        >>> lst = ['a', 'b', 'c', 'b']
 793        >>> it(lst).last_index_of_or('b', 0)
 794        3
 795
 796        Example 2:
 797        >>> lst = ['a', 'b', 'c']
 798        >>> it(lst).last_index_of_or('d', len(lst))
 799        3
 800        """
 801        return none_or(self.last_index_of_or_none(element), default)
 802
 803    def last_index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
 804        """
 805         Returns last index of [element], or computes the value from a callback if the collection does not contain element.
 806
 807        Example 1:
 808        >>> lst = ['a', 'b', 'c', 'b']
 809        >>> it(lst).last_index_of_or_else('b', lambda: 0)
 810        3
 811
 812        Example 2:
 813        >>> lst = ['a', 'b', 'c']
 814        >>> it(lst).last_index_of_or_else('d', lambda: len(lst))
 815        3
 816        """
 817        return none_or_else(self.last_index_of_or_none(element), f)
 818
 819    @overload
 820    def index_of_first_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ...
 821    @overload
 822    def index_of_first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ...
 823    @overload
 824    def index_of_first_or_none(
 825        self, predicate: Callable[[T, int, Stream[T]], bool]
 826    ) -> Optional[int]: ...
 827    def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
 828        """
 829        Returns first index of element matching the given [predicate], or None if no such element was found.
 830
 831        Example 1:
 832        >>> lst = ['a', 'b', 'c']
 833        >>> it(lst).index_of_first_or_none(lambda x: x == 'b')
 834        1
 835
 836        Example 2:
 837        >>> lst = ['a', 'b', 'c']
 838        >>> it(lst).index_of_first_or_none(lambda x: x == 'd')
 839        """
 840        predicate = self.__callback_overload_warpper__(predicate)
 841        for i, x in enumerate(self):
 842            if predicate(x):
 843                return i
 844        return None
 845
 846    @overload
 847    def index_of_first(self, predicate: Callable[[T], bool]) -> int: ...
 848    @overload
 849    def index_of_first(self, predicate: Callable[[T, int], bool]) -> int: ...
 850    @overload
 851    def index_of_first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
 852    def index_of_first(self, predicate: Callable[..., bool]) -> int:
 853        """
 854        Returns first index of element matching the given [predicate], or -1 if no such element was found.
 855
 856        Example 1:
 857        >>> lst = ['a', 'b', 'c']
 858        >>> it(lst).index_of_first(lambda x: x == 'b')
 859        1
 860
 861        Example 2:
 862        >>> lst = ['a', 'b', 'c']
 863        >>> it(lst).index_of_first(lambda x: x == 'd')
 864        -1
 865
 866        Example 3:
 867        >>> lst = ['a', 'b', 'c']
 868        >>> it(lst).index_of_first(lambda x: x == 'a')
 869        0
 870        """
 871        return none_or(self.index_of_first_or_none(predicate), -1)
 872
 873    @overload
 874    def index_of_first_or(self, predicate: Callable[[T], bool], default: int) -> int: ...
 875    @overload
 876    def index_of_first_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ...
 877    @overload
 878    def index_of_first_or(
 879        self, predicate: Callable[[T, int, Stream[T]], bool], default: int
 880    ) -> int: ...
 881    def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int:
 882        """
 883        Returns first index of element matching the given [predicate], or default value if no such element was found.
 884
 885        Example 1:
 886        >>> lst = ['a', 'b', 'c']
 887        >>> it(lst).index_of_first_or(lambda x: x == 'b', 0)
 888        1
 889
 890        Example 2:
 891        >>> lst = ['a', 'b', 'c']
 892        >>> it(lst).index_of_first_or(lambda x: x == 'd', 0)
 893        0
 894
 895        Example 3:
 896        >>> lst = ['a', 'b', 'c']
 897        >>> it(lst).index_of_first_or(lambda x: x == 'a', 0)
 898        0
 899        """
 900        return none_or(self.index_of_first_or_none(predicate), default)
 901
 902    @overload
 903    def index_of_first_or_else(
 904        self, predicate: Callable[[T], bool], f: Callable[[], int]
 905    ) -> int: ...
 906    @overload
 907    def index_of_first_or_else(
 908        self, predicate: Callable[[T, int], bool], f: Callable[[], int]
 909    ) -> int: ...
 910    @overload
 911    def index_of_first_or_else(
 912        self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int]
 913    ) -> int: ...
 914    def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
 915        """
 916        Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found.
 917
 918        Example 1:
 919        >>> lst = ['a', 'b', 'c']
 920        >>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst))
 921        1
 922
 923        Example 2:
 924        >>> lst = ['a', 'b', 'c']
 925        >>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst))
 926        3
 927
 928        Example 3:
 929        >>> lst = ['a', 'b', 'c']
 930        >>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst))
 931        0
 932        """
 933        return none_or_else(self.index_of_first_or_none(predicate), f)
 934
 935    @overload
 936    def index_of_last_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ...
 937    @overload
 938    def index_of_last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ...
 939    @overload
 940    def index_of_last_or_none(
 941        self, predicate: Callable[[T, int, Stream[T]], bool]
 942    ) -> Optional[int]: ...
 943    def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
 944        """
 945        Returns last index of element matching the given [predicate], or -1 if no such element was found.
 946
 947        Example 1:
 948        >>> lst = ['a', 'b', 'c', 'b']
 949        >>> it(lst).index_of_last_or_none(lambda x: x == 'b')
 950        3
 951
 952        Example 2:
 953        >>> lst = ['a', 'b', 'c']
 954        >>> it(lst).index_of_last_or_none(lambda x: x == 'd')
 955        """
 956        seq = self.reversed()
 957        last_idx = len(seq) - 1
 958        predicate = self.__callback_overload_warpper__(predicate)
 959        for i, x in enumerate(seq):
 960            if predicate(x):
 961                return last_idx - i
 962        return None
 963
 964    @overload
 965    def index_of_last(self, predicate: Callable[[T], bool]) -> int: ...
 966    @overload
 967    def index_of_last(self, predicate: Callable[[T, int], bool]) -> int: ...
 968    @overload
 969    def index_of_last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
 970    def index_of_last(self, predicate: Callable[..., bool]) -> int:
 971        """
 972        Returns last index of element matching the given [predicate], or -1 if no such element was found.
 973
 974        Example 1:
 975        >>> lst = ['a', 'b', 'c', 'b']
 976        >>> it(lst).index_of_last(lambda x: x == 'b')
 977        3
 978
 979        Example 2:
 980        >>> lst = ['a', 'b', 'c']
 981        >>> it(lst).index_of_last(lambda x: x == 'd')
 982        -1
 983
 984        Example 3:
 985        >>> lst = ['a', 'b', 'c']
 986        >>> it(lst).index_of_last(lambda x: x == 'a')
 987        0
 988        """
 989        return none_or(self.index_of_last_or_none(predicate), -1)
 990
 991    @overload
 992    def index_of_last_or(self, predicate: Callable[[T], bool], default: int) -> int: ...
 993    @overload
 994    def index_of_last_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ...
 995    @overload
 996    def index_of_last_or(
 997        self, predicate: Callable[[T, int, Stream[T]], bool], default: int
 998    ) -> int: ...
 999    def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int:
1000        """
1001        Returns last index of element matching the given [predicate], or default value if no such element was found.
1002
1003        Example 1:
1004        >>> lst = ['a', 'b', 'c', 'b']
1005        >>> it(lst).index_of_last_or(lambda x: x == 'b', 0)
1006        3
1007
1008        Example 2:
1009        >>> lst = ['a', 'b', 'c']
1010        >>> it(lst).index_of_last_or(lambda x: x == 'd', -99)
1011        -99
1012
1013        Example 3:
1014        >>> lst = ['a', 'b', 'c']
1015        >>> it(lst).index_of_last_or(lambda x: x == 'a', 0)
1016        0
1017        """
1018        return none_or(self.index_of_last_or_none(predicate), default)
1019
1020    @overload
1021    def index_of_last_or_else(
1022        self, predicate: Callable[[T], bool], f: Callable[[], int]
1023    ) -> int: ...
1024    @overload
1025    def index_of_last_or_else(
1026        self, predicate: Callable[[T, int], bool], f: Callable[[], int]
1027    ) -> int: ...
1028    @overload
1029    def index_of_last_or_else(
1030        self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int]
1031    ) -> int: ...
1032    def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
1033        """
1034        Returns last index of element matching the given [predicate], or default value if no such element was found.
1035
1036        Example 1:
1037        >>> lst = ['a', 'b', 'c', 'b']
1038        >>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst))
1039        3
1040
1041        Example 2:
1042        >>> lst = ['a', 'b', 'c']
1043        >>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst))
1044        -3
1045
1046        Example 3:
1047        >>> lst = ['a', 'b', 'c']
1048        >>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst))
1049        0
1050        """
1051        return none_or_else(self.index_of_last_or_none(predicate), f)
1052
1053    @overload
1054    def single(self) -> T: ...
1055    @overload
1056    def single(self, predicate: Callable[[T], bool]) -> T: ...
1057    @overload
1058    def single(self, predicate: Callable[[T, int], bool]) -> T: ...
1059    @overload
1060    def single(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
1061    def single(self, predicate: Optional[Callable[..., bool]] = None) -> T:
1062        """
1063        Returns the single element matching the given [predicate], or throws exception if there is no
1064        or more than one matching element.
1065
1066        Exmaple 1:
1067        >>> lst = ['a']
1068        >>> it(lst).single()
1069        'a'
1070
1071        Exmaple 2:
1072        >>> lst = []
1073        >>> it(lst).single() is None
1074        Traceback (most recent call last):
1075        ...
1076        ValueError: Stream contains no element matching the predicate.
1077
1078        Exmaple 2:
1079        >>> lst = ['a', 'b']
1080        >>> it(lst).single() is None
1081        Traceback (most recent call last):
1082        ...
1083        ValueError: Stream contains more than one matching element.
1084        """
1085        single: Optional[T] = None
1086        found = False
1087        for i in self if predicate is None else self.filter(predicate):
1088            if found:
1089                raise ValueError("Stream contains more than one matching element.")
1090            single = i
1091            found = True
1092        if single is None:
1093            raise ValueError("Stream contains no element matching the predicate.")
1094        return single
1095
1096    @overload
1097    def single_or_none(self) -> Optional[T]: ...
1098    @overload
1099    def single_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
1100    @overload
1101    def single_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
1102    @overload
1103    def single_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
1104    def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
1105        """
1106        Returns the single element matching the given [predicate], or `None` if element was not found
1107        or more than one element was found.
1108
1109        Exmaple 1:
1110        >>> lst = ['a']
1111        >>> it(lst).single_or_none()
1112        'a'
1113
1114        Exmaple 2:
1115        >>> lst = []
1116        >>> it(lst).single_or_none()
1117
1118        Exmaple 2:
1119        >>> lst = ['a', 'b']
1120        >>> it(lst).single_or_none()
1121
1122        """
1123        single: Optional[T] = None
1124        found = False
1125        for i in self if predicate is None else self.filter(predicate):
1126            if found:
1127                return None
1128            single = i
1129            found = True
1130        if not found:
1131            return None
1132        return single
1133
1134    # noinspection PyShadowingNames
1135    def drop(self, n: int) -> Stream[T]:
1136        """
1137        Returns a Stream containing all elements except first [n] elements.
1138
1139        Example 1:
1140        >>> lst = ['a', 'b', 'c']
1141        >>> it(lst).drop(0).to_list()
1142        ['a', 'b', 'c']
1143
1144        Example 2:
1145        >>> lst = ['a', 'b', 'c']
1146        >>> it(lst).drop(1).to_list()
1147        ['b', 'c']
1148
1149        Example 2:
1150        >>> lst = ['a', 'b', 'c']
1151        >>> it(lst).drop(4).to_list()
1152        []
1153        """
1154        if n < 0:
1155            raise ValueError(f"Requested element count {n} is less than zero.")
1156        if n == 0:
1157            return self
1158
1159        from .drop import DropTransform
1160
1161        return it(DropTransform(self, n))
1162
1163    # noinspection PyShadowingNames
1164    @overload
1165    def drop_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1166    @overload
1167    def drop_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1168    @overload
1169    def drop_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1170    def drop_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1171        """
1172        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1173
1174        Example 1:
1175        >>> lst = [1, 2, 3, 4, 1]
1176        >>> it(lst).drop_while(lambda x: x < 3 ).to_list()
1177        [3, 4, 1]
1178        """
1179        from .drop_while import DropWhileTransform
1180
1181        return it(DropWhileTransform(self, self.__callback_overload_warpper__(predicate)))
1182
1183    # noinspection PyShadowingNames
1184    @overload
1185    def drop_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1186    @overload
1187    def drop_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1188    @overload
1189    def drop_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1190    def drop_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1191        """
1192        Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate].
1193
1194        Example 1:
1195        >>> lst = [1, 2, 3, 4, 1]
1196        >>> it(lst).drop_until(lambda x: x >= 3).to_list()
1197        [3, 4, 1]
1198
1199        Example 2:
1200        >>> lst = [1, 2, 1, 4]
1201        >>> it(lst).drop_until(lambda x: x == 4).to_list()
1202        [4]
1203        """
1204        from .drop_until import DropUntilTransform
1205
1206        return it(DropUntilTransform(self, self.__callback_overload_warpper__(predicate)))
1207
1208    def drop_last(self, n: int) -> Stream[T]:
1209        """
1210        Returns a Stream containing all elements except last [n] elements.
1211
1212        Example 1:
1213        >>> lst = ['a', 'b', 'c']
1214        >>> it(lst).drop_last(0).to_list()
1215        ['a', 'b', 'c']
1216
1217        Example 2:
1218        >>> lst = ['a', 'b', 'c']
1219        >>> it(lst).drop_last(1).to_list()
1220        ['a', 'b']
1221
1222        Example 3:
1223        >>> lst = ['a', 'b', 'c']
1224        >>> it(lst).drop_last(4).to_list()
1225        []
1226        """
1227        if n < 0:
1228            raise ValueError(f"Requested element count {n} is less than zero.")
1229        if n == 0:
1230            return self
1231
1232        size = len(self)
1233        if size <= n:
1234            return Stream([])
1235        return self.take(size - n)
1236
1237    def skip(self, n: int) -> Stream[T]:
1238        """
1239        Returns a Stream containing all elements except first [n] elements.
1240
1241        Example 1:
1242        >>> lst = ['a', 'b', 'c']
1243        >>> it(lst).skip(0).to_list()
1244        ['a', 'b', 'c']
1245
1246         Example 2:
1247        >>> lst = ['a', 'b', 'c']
1248        >>> it(lst).skip(1).to_list()
1249        ['b', 'c']
1250
1251        Example 2:
1252        >>> lst = ['a', 'b', 'c']
1253        >>> it(lst).skip(4).to_list()
1254        []
1255        """
1256        return self.drop(n)
1257
1258    @overload
1259    def skip_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1260    @overload
1261    def skip_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1262    @overload
1263    def skip_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1264    def skip_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1265        """
1266        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1267
1268        Example 1:
1269        >>> lst = [1, 2, 3, 4, 1]
1270        >>> it(lst).skip_while(lambda x: x < 3 ).to_list()
1271        [3, 4, 1]
1272        """
1273        return self.drop_while(predicate)
1274
1275    def take(self, n: int) -> Stream[T]:
1276        """
1277        Returns an Stream containing first [n] elements.
1278
1279        Example 1:
1280        >>> a = ['a', 'b', 'c']
1281        >>> it(a).take(0).to_list()
1282        []
1283
1284        Example 2:
1285        >>> a = ['a', 'b', 'c']
1286        >>> it(a).take(2).to_list()
1287        ['a', 'b']
1288        """
1289        if n < 0:
1290            raise ValueError(f"Requested element count {n} is less than zero.")
1291        if n == 0:
1292            return Stream([])
1293        from .take import TakeTransform
1294
1295        return it(TakeTransform(self, n))
1296
1297    # noinspection PyShadowingNames
1298    @overload
1299    def take_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1300    @overload
1301    def take_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1302    @overload
1303    def take_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1304    def take_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1305        """
1306        Returns an Stream containing first elements satisfying the given [predicate].
1307
1308        Example 1:
1309        >>> lst = ['a', 'b', 'c', 'd']
1310        >>> it(lst).take_while(lambda x: x in ['a', 'b']).to_list()
1311        ['a', 'b']
1312        """
1313        from .take_while import TakeWhileTransform
1314
1315        return it(TakeWhileTransform(self, self.__callback_overload_warpper__(predicate)))
1316
1317    # noinspection PyShadowingNames
1318    @overload
1319    def take_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1320    @overload
1321    def take_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1322    @overload
1323    def take_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1324    def take_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1325        """
1326        Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate].
1327
1328        Example 1:
1329        >>> lst = [1, 2, 3, 4]
1330        >>> it(lst).take_until(lambda x: x > 2).to_list()
1331        [1, 2]
1332
1333        Example 2:
1334        >>> lst = [1, 2, 3, 4]
1335        >>> it(lst).take_until(lambda x: x > 10).to_list()
1336        [1, 2, 3, 4]
1337        """
1338        from .take_until import TakeUntilTransform
1339
1340        return it(TakeUntilTransform(self, self.__callback_overload_warpper__(predicate)))
1341
1342    def take_last(self, n: int) -> Stream[T]:
1343        """
1344        Returns an Stream containing last [n] elements.
1345
1346        Example 1:
1347        >>> a = ['a', 'b', 'c']
1348        >>> it(a).take_last(0).to_list()
1349        []
1350
1351        Example 2:
1352        >>> a = ['a', 'b', 'c']
1353        >>> it(a).take_last(2).to_list()
1354        ['b', 'c']
1355
1356        Example 3:
1357        >>> a = ['a', 'b', 'c']
1358        >>> it(a).take_last(10).to_list()
1359        ['a', 'b', 'c']
1360        """
1361        if n < 0:
1362            raise ValueError(f"Requested element count {n} is less than zero.")
1363        if n == 0:
1364            return Stream([])
1365
1366        return self.drop(max(len(self) - n, 0))
1367
1368    # noinspection PyShadowingNames
1369    def sorted(self) -> Stream[T]:
1370        """
1371        Returns an Stream that yields elements of this Stream sorted according to their natural sort order.
1372
1373        Example 1:
1374        >>> lst = ['b', 'a', 'e', 'c']
1375        >>> it(lst).sorted().to_list()
1376        ['a', 'b', 'c', 'e']
1377
1378         Example 2:
1379        >>> lst = [2, 1, 4, 3]
1380        >>> it(lst).sorted().to_list()
1381        [1, 2, 3, 4]
1382        """
1383        lst = list(self)
1384        lst.sort()  # type: ignore
1385        return it(lst)
1386
1387    # noinspection PyShadowingNames
1388    @overload
1389    def sorted_by(self, key_selector: Callable[[T], SupportsRichComparisonT]) -> Stream[T]: ...
1390    @overload
1391    def sorted_by(self, key_selector: Callable[[T, int], SupportsRichComparisonT]) -> Stream[T]: ...
1392    @overload
1393    def sorted_by(
1394        self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT]
1395    ) -> Stream[T]: ...
1396    def sorted_by(self, key_selector: Callable[..., SupportsRichComparisonT]) -> Stream[T]:
1397        """
1398        Returns a sequence that yields elements of this sequence sorted according to natural sort
1399        order of the value returned by specified [key_selector] function.
1400
1401        Example 1:
1402        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1403        >>> it(lst).sorted_by(lambda x: x['name']).to_list()
1404        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1405        >>> it(lst).sorted_by(lambda x: x['age']).to_list()
1406        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1407        """
1408        lst = list(self)
1409        lst.sort(key=self.__callback_overload_warpper__(key_selector))
1410        return it(lst)
1411
1412    def sorted_descending(self) -> Stream[T]:
1413        """
1414        Returns a Stream of all elements sorted descending according to their natural sort order.
1415
1416        Example 1:
1417        >>> lst = ['b', 'c', 'a']
1418        >>> it(lst).sorted_descending().to_list()
1419        ['c', 'b', 'a']
1420        """
1421        return self.sorted().reversed()
1422
1423    @overload
1424    def sorted_by_descending(
1425        self, key_selector: Callable[[T], SupportsRichComparisonT]
1426    ) -> Stream[T]: ...
1427    @overload
1428    def sorted_by_descending(
1429        self, key_selector: Callable[[T, int], SupportsRichComparisonT]
1430    ) -> Stream[T]: ...
1431    @overload
1432    def sorted_by_descending(
1433        self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT]
1434    ) -> Stream[T]: ...
1435    def sorted_by_descending(
1436        self, key_selector: Callable[..., SupportsRichComparisonT]
1437    ) -> Stream[T]:
1438        """
1439        Returns a sequence that yields elements of this sequence sorted descending according
1440        to natural sort order of the value returned by specified [key_selector] function.
1441
1442        Example 1:
1443        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1444        >>> it(lst).sorted_by_descending(lambda x: x['name']).to_list()
1445        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1446        >>> it(lst).sorted_by_descending(lambda x: x['age']).to_list()
1447        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1448        """
1449        return self.sorted_by(key_selector).reversed()
1450
1451    # noinspection PyShadowingNames
1452    def sorted_with(self, comparator: Callable[[T, T], int]) -> Stream[T]:
1453        """
1454        Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
1455
1456        Example 1:
1457        >>> lst = ['aa', 'bbb', 'c']
1458        >>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list()
1459        ['c', 'aa', 'bbb']
1460        """
1461        from functools import cmp_to_key
1462
1463        lst = list(self)
1464        lst.sort(key=cmp_to_key(comparator))
1465        return it(lst)
1466
1467    @overload
1468    def associate(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ...
1469    @overload
1470    def associate(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ...
1471    @overload
1472    def associate(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ...
1473    def associate(self, transform: Callable[..., Tuple[K, V]]) -> Dict[K, V]:
1474        """
1475        Returns a [Dict] containing key-value Tuple provided by [transform] function
1476        applied to elements of the given Stream.
1477
1478        Example 1:
1479        >>> lst = ['1', '2', '3']
1480        >>> it(lst).associate(lambda x: (int(x), x))
1481        {1: '1', 2: '2', 3: '3'}
1482        """
1483        transform = self.__callback_overload_warpper__(transform)
1484        dic: Dict[K, V] = dict()
1485        for i in self:
1486            k, v = transform(i)
1487            dic[k] = v
1488        return dic
1489
1490    @overload
1491    def associate_by(self, key_selector: Callable[[T], K]) -> Dict[K, T]: ...
1492    @overload
1493    def associate_by(self, key_selector: Callable[[T, int], K]) -> Dict[K, T]: ...
1494    @overload
1495    def associate_by(self, key_selector: Callable[[T, int, Stream[T]], K]) -> Dict[K, T]: ...
1496    @overload
1497    def associate_by(
1498        self, key_selector: Callable[[T], K], value_transform: Callable[[T], V]
1499    ) -> Dict[K, V]: ...
1500    def associate_by(
1501        self,
1502        key_selector: Callable[..., K],
1503        value_transform: Optional[Callable[[T], V]] = None,
1504    ) -> Union[Dict[K, T], Dict[K, V]]:
1505        """
1506        Returns a [Dict] containing key-value Tuple provided by [transform] function
1507        applied to elements of the given Stream.
1508
1509        Example 1:
1510        >>> lst = ['1', '2', '3']
1511        >>> it(lst).associate_by(lambda x: int(x))
1512        {1: '1', 2: '2', 3: '3'}
1513
1514        Example 2:
1515        >>> lst = ['1', '2', '3']
1516        >>> it(lst).associate_by(lambda x: int(x), lambda x: x+x)
1517        {1: '11', 2: '22', 3: '33'}
1518
1519        """
1520        key_selector = self.__callback_overload_warpper__(key_selector)
1521
1522        dic: Dict[K, Any] = dict()
1523        for i in self:
1524            k = key_selector(i)
1525            dic[k] = i if value_transform is None else value_transform(i)
1526        return dic
1527
1528    @overload
1529    def associate_by_to(
1530        self, destination: Dict[K, T], key_selector: Callable[[T], K]
1531    ) -> Dict[K, T]: ...
1532    @overload
1533    def associate_by_to(
1534        self,
1535        destination: Dict[K, V],
1536        key_selector: Callable[[T], K],
1537        value_transform: Callable[[T], V],
1538    ) -> Dict[K, V]: ...
1539    def associate_by_to(
1540        self,
1541        destination: Dict[K, Any],
1542        key_selector: Callable[[T], K],
1543        value_transform: Optional[Callable[[T], Any]] = None,
1544    ) -> Dict[K, Any]:
1545        """
1546        Returns a [Dict] containing key-value Tuple provided by [transform] function
1547        applied to elements of the given Stream.
1548
1549        Example 1:
1550        >>> lst = ['1', '2', '3']
1551        >>> it(lst).associate_by_to({}, lambda x: int(x))
1552        {1: '1', 2: '2', 3: '3'}
1553
1554        Example 2:
1555        >>> lst = ['1', '2', '3']
1556        >>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' )
1557        {1: '1!', 2: '2!', 3: '3!'}
1558
1559        """
1560        for i in self:
1561            k = key_selector(i)
1562            destination[k] = i if value_transform is None else value_transform(i)
1563        return destination
1564
1565    @overload
1566    def all(self, predicate: Callable[[T], bool]) -> bool: ...
1567    @overload
1568    def all(self, predicate: Callable[[T, int], bool]) -> bool: ...
1569    @overload
1570    def all(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ...
1571    def all(self, predicate: Callable[..., bool]) -> bool:
1572        """
1573        Returns True if all elements of the Stream satisfy the specified [predicate] function.
1574
1575        Example 1:
1576        >>> lst = [1, 2, 3]
1577        >>> it(lst).all(lambda x: x > 0)
1578        True
1579        >>> it(lst).all(lambda x: x > 1)
1580        False
1581        """
1582        predicate = self.__callback_overload_warpper__(predicate)
1583        for i in self:
1584            if not predicate(i):
1585                return False
1586        return True
1587
1588    @overload
1589    def any(self, predicate: Callable[[T], bool]) -> bool: ...
1590    @overload
1591    def any(self, predicate: Callable[[T, int], bool]) -> bool: ...
1592    @overload
1593    def any(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ...
1594    def any(self, predicate: Callable[..., bool]) -> bool:
1595        """
1596        Returns True if any elements of the Stream satisfy the specified [predicate] function.
1597
1598        Example 1:
1599        >>> lst = [1, 2, 3]
1600        >>> it(lst).any(lambda x: x > 0)
1601        True
1602        >>> it(lst).any(lambda x: x > 3)
1603        False
1604        """
1605        predicate = self.__callback_overload_warpper__(predicate)
1606        for i in self:
1607            if predicate(i):
1608                return True
1609        return False
1610
1611    @overload
1612    def count(self) -> int: ...
1613    @overload
1614    def count(self, predicate: Callable[[T], bool]) -> int: ...
1615    @overload
1616    def count(self, predicate: Callable[[T, int], bool]) -> int: ...
1617    @overload
1618    def count(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
1619    def count(self, predicate: Optional[Callable[..., bool]] = None) -> int:
1620        """
1621        Returns the number of elements in the Stream that satisfy the specified [predicate] function.
1622
1623        Example 1:
1624        >>> lst = [1, 2, 3]
1625        >>> it(lst).count()
1626        3
1627        >>> it(lst).count(lambda x: x > 0)
1628        3
1629        >>> it(lst).count(lambda x: x > 2)
1630        1
1631        """
1632        if predicate is None:
1633            return len(self)
1634        predicate = self.__callback_overload_warpper__(predicate)
1635        return sum(1 for i in self if predicate(i))
1636
1637    def contains(self, value: T) -> bool:
1638        """
1639        Returns True if the Stream contains the specified [value].
1640
1641        Example 1:
1642        >>> lst = [1, 2, 3]
1643        >>> it(lst).contains(1)
1644        True
1645        >>> it(lst).contains(4)
1646        False
1647        """
1648        return value in self
1649
1650    def element_at(self, index: int) -> T:
1651        """
1652        Returns the element at the specified [index] in the Stream.
1653
1654        Example 1:
1655        >>> lst = [1, 2, 3]
1656        >>> it(lst).element_at(1)
1657        2
1658
1659        Example 2:
1660        >>> lst = [1, 2, 3]
1661        >>> it(lst).element_at(3)
1662        Traceback (most recent call last):
1663        ...
1664        IndexError: Index 3 out of range
1665        """
1666        return self.element_at_or_else(
1667            index, lambda index: throw(IndexError(f"Index {index} out of range"))
1668        )
1669
1670    @overload
1671    def element_at_or_else(self, index: int) -> Optional[T]:
1672        """
1673        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1674
1675        Example 1:
1676        >>> lst = [1, 2, 3]
1677        >>> it(lst).element_at_or_else(1, 'default')
1678        2
1679        >>> it(lst).element_at_or_else(4, lambda x: 'default')
1680        'default'
1681        """
1682        ...
1683
1684    @overload
1685    def element_at_or_else(self, index: int, default: T) -> T: ...
1686    @overload
1687    def element_at_or_else(self, index: int, default: Callable[[int], T]) -> T: ...
1688    def element_at_or_else(
1689        self, index: int, default: Union[Callable[[int], T], T, None] = None
1690    ) -> Optional[T]:
1691        """
1692        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1693
1694        Example 1:
1695        >>> lst = [1, 2, 3]
1696        >>> it(lst).element_at_or_else(1, lambda x: 'default')
1697        2
1698        >>> it(lst).element_at_or_else(4, lambda x: 'default')
1699        'default'
1700
1701        """
1702        if index >= 0:
1703            if (
1704                isinstance(self.__transform__, NonTransform)
1705                and isinstance(self.__transform__.iter, list)
1706                and index < len(self.__transform__.iter)
1707            ):
1708                return self.__transform__.iter[index]
1709            for i, e in enumerate(self):
1710                if i == index:
1711                    return e
1712        return default(index) if callable(default) else default  # type: ignore
1713
1714    def element_at_or_default(self, index: int, default: T) -> T:
1715        """
1716        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1717
1718        Example 1:
1719        >>> lst = [1, 2, 3]
1720        >>> it(lst).element_at_or_default(1, 'default')
1721        2
1722        >>> it(lst).element_at_or_default(4, 'default')
1723        'default'
1724
1725        """
1726        return self.element_at_or_else(index, default)
1727
1728    def element_at_or_none(self, index: int) -> Optional[T]:
1729        """
1730        Returns the element at the specified [index] in the Stream or None if the index is out of bounds.
1731
1732        Example 1:
1733        >>> lst = [1, 2, 3]
1734        >>> it(lst).element_at_or_none(1)
1735        2
1736        >>> it(lst).element_at_or_none(4) is None
1737        True
1738        """
1739        return self.element_at_or_else(index)
1740
1741    def distinct(self) -> Stream[T]:
1742        """
1743        Returns a new Stream containing the distinct elements of the given Stream.
1744
1745        Example 1:
1746        >>> lst = [1, 2, 3, 1, 2, 3]
1747        >>> it(lst).distinct().to_list()
1748        [1, 2, 3]
1749
1750        Example 2:
1751        >>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1752        >>> it(lst).distinct().sorted().to_list()
1753        [(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1754
1755        """
1756        from .distinct import DistinctTransform
1757
1758        return it(DistinctTransform(self))
1759
1760    @overload
1761    def distinct_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ...
1762    @overload
1763    def distinct_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ...
1764    @overload
1765    def distinct_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ...
1766    def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
1767        """
1768        Returns a new Stream containing the distinct elements of the given Stream.
1769
1770        Example 1:
1771        >>> lst = [1, 2, 3, 1, 2, 3]
1772        >>> it(lst).distinct_by(lambda x: x%2).to_list()
1773        [1, 2]
1774        """
1775        from .distinct import DistinctTransform
1776
1777        return it(DistinctTransform(self, self.__callback_overload_warpper__(key_selector)))
1778
1779    @overload
1780    def reduce(self, accumulator: Callable[[T, T], T]) -> T: ...
1781    @overload
1782    def reduce(self, accumulator: Callable[[U, T], U], initial: U) -> U: ...
1783    def reduce(self, accumulator: Callable[..., U], initial: Optional[U] = None) -> Optional[U]:
1784        """
1785        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1786
1787        Example 1:
1788        >>> lst = [1, 2, 3]
1789        >>> it(lst).reduce(lambda x, y: x+y)
1790        6
1791        """
1792        result: Optional[U] = initial
1793        for i, e in enumerate(self):
1794            if i == 0 and initial is None:
1795                result = e  # type: ignore
1796                continue
1797
1798            result = accumulator(result, e)
1799        return result
1800
1801    def fold(self, initial: U, accumulator: Callable[[U, T], U]) -> U:
1802        """
1803        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1804
1805        Example 1:
1806        >>> lst = [1, 2, 3]
1807        >>> it(lst).fold(0, lambda x, y: x+y)
1808        6
1809        """
1810        return self.reduce(accumulator, initial)
1811
1812    @overload
1813    def sum_of(self, selector: Callable[[T], int]) -> int: ...
1814    @overload
1815    def sum_of(self, selector: Callable[[T], float]) -> float: ...
1816    def sum_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1817        """
1818        Returns the sum of the elements of the given Stream.
1819
1820        Example 1:
1821        >>> lst = [1, 2, 3]
1822        >>> it(lst).sum_of(lambda x: x)
1823        6
1824        """
1825        return sum(selector(i) for i in self)
1826
1827    @overload
1828    def max_of(self, selector: Callable[[T], int]) -> int: ...
1829    @overload
1830    def max_of(self, selector: Callable[[T], float]) -> float: ...
1831    def max_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1832        """
1833        Returns the maximum element of the given Stream.
1834
1835        Example 1:
1836        >>> lst = [1, 2, 3]
1837        >>> it(lst).max_of(lambda x: x)
1838        3
1839        """
1840        return max(selector(i) for i in self)
1841
1842    @overload
1843    def max_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ...
1844    @overload
1845    def max_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ...
1846    def max_by_or_none(self, selector: Callable[[T], Union[float, int]]) -> Optional[T]:
1847        """
1848        Returns the first element yielding the largest value of the given function
1849        or `none` if there are no elements.
1850
1851        Example 1:
1852        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1853        >>> it(lst).max_by_or_none(lambda x: x["num"])
1854        {'name': 'B', 'num': 200}
1855
1856        Example 2:
1857        >>> lst = []
1858        >>> it(lst).max_by_or_none(lambda x: x["num"])
1859        """
1860
1861        max_item = None
1862        max_val = None
1863
1864        for item in self:
1865            val = selector(item)
1866            if max_val is None or val > max_val:
1867                max_item = item
1868                max_val = val
1869
1870        return max_item
1871
1872    @overload
1873    def max_by(self, selector: Callable[[T], int]) -> T: ...
1874    @overload
1875    def max_by(self, selector: Callable[[T], float]) -> T: ...
1876    def max_by(self, selector: Callable[[T], Union[float, int]]) -> T:
1877        """
1878        Returns the first element yielding the largest value of the given function.
1879
1880        Example 1:
1881        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1882        >>> it(lst).max_by(lambda x: x["num"])
1883        {'name': 'B', 'num': 200}
1884
1885        Exmaple 2:
1886        >>> lst = []
1887        >>> it(lst).max_by(lambda x: x["num"])
1888        Traceback (most recent call last):
1889        ...
1890        ValueError: Stream is empty.
1891        """
1892        max_item = self.max_by_or_none(selector)
1893        if max_item is None:
1894            raise ValueError("Stream is empty.")
1895        return max_item
1896
1897    @overload
1898    def min_of(self, selector: Callable[[T], int]) -> int:
1899        """
1900        Returns the minimum element of the given Stream.
1901
1902        Example 1:
1903        >>> lst = [1, 2, 3]
1904        >>> it(lst).min_of(lambda x: x)
1905        1
1906        """
1907        ...
1908
1909    @overload
1910    def min_of(self, selector: Callable[[T], float]) -> float: ...
1911    def min_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1912        return min(selector(i) for i in self)
1913
1914    @overload
1915    def min_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ...
1916    @overload
1917    def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ...
1918    def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]:
1919        """
1920        Returns the first element yielding the smallest value of the given function
1921        or `none` if there are no elements.
1922
1923        Example 1:
1924        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1925        >>> it(lst).min_by_or_none(lambda x: x["num"])
1926        {'name': 'A', 'num': 100}
1927
1928        Exmaple 2:
1929        >>> lst = []
1930        >>> it(lst).min_by_or_none(lambda x: x["num"])
1931        """
1932        min_item = None
1933        min_val = None
1934
1935        for item in self:
1936            val = selector(item)
1937            if min_val is None or val < min_val:
1938                min_item = item
1939                min_val = val
1940
1941        return min_item
1942
1943    @overload
1944    def min_by(self, selector: Callable[[T], int]) -> T: ...
1945    @overload
1946    def min_by(self, selector: Callable[[T], float]) -> T: ...
1947    def min_by(self, selector: Callable[[T], float]) -> T:
1948        """
1949        Returns the first element yielding the smallest value of the given function.
1950
1951        Example 1:
1952        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1953        >>> it(lst).min_by(lambda x: x["num"])
1954        {'name': 'A', 'num': 100}
1955
1956        Exmaple 2:
1957        >>> lst = []
1958        >>> it(lst).min_by(lambda x: x["num"])
1959        Traceback (most recent call last):
1960        ...
1961        ValueError: Stream is empty.
1962        """
1963        min_item = self.min_by_or_none(selector)
1964        if min_item is None:
1965            raise ValueError("Stream is empty.")
1966
1967        return min_item
1968
1969    def mean_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1970        """
1971        Returns the mean of the elements of the given Stream.
1972
1973        Example 1:
1974        >>> lst = [1, 2, 3]
1975        >>> it(lst).mean_of(lambda x: x)
1976        2.0
1977        """
1978        return self.sum_of(selector) / len(self)
1979
1980    @overload
1981    def sum(self: Stream[int]) -> int:
1982        """
1983        Returns the sum of the elements of the given Stream.
1984
1985        Example 1:
1986        >>> lst = [1, 2, 3]
1987        >>> it(lst).sum()
1988        6
1989        """
1990        ...
1991
1992    @overload
1993    def sum(self: Stream[float]) -> float: ...
1994    def sum(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
1995        """
1996        Returns the sum of the elements of the given Stream.
1997
1998        Example 1:
1999        >>> lst = [1, 2, 3]
2000        >>> it(lst).sum()
2001        6
2002        """
2003        return sum(self)
2004
2005    @overload
2006    def max(self: Stream[int]) -> int: ...
2007    @overload
2008    def max(self: Stream[float]) -> float: ...
2009    def max(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2010        """
2011        Returns the maximum element of the given Stream.
2012
2013        Example 1:
2014        >>> lst = [1, 2, 3]
2015        >>> it(lst).max()
2016        3
2017        """
2018        return max(self)
2019
2020    @overload
2021    def max_or_default(self: Stream[int]) -> int: ...
2022    @overload
2023    def max_or_default(self: Stream[int], default: V) -> Union[int, V]: ...
2024    @overload
2025    def max_or_default(self: Stream[float]) -> float: ...
2026    @overload
2027    def max_or_default(self: Stream[float], default: V) -> Union[float, V]: ...
2028    def max_or_default(
2029        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2030    ) -> Union[float, int, V, None]:
2031        """
2032        Returns the maximum element of the given Stream.
2033
2034        Example 1:
2035        >>> lst = [1, 2, 3]
2036        >>> it(lst).max_or_default()
2037        3
2038
2039        Example 2:
2040        >>> lst = []
2041        >>> it(lst).max_or_default() is None
2042        True
2043
2044        Example 3:
2045        >>> lst = []
2046        >>> it(lst).max_or_default(9)
2047        9
2048        """
2049        if self.is_empty():
2050            return default
2051        return max(self)
2052
2053    @overload
2054    def max_or_none(self: Stream[int]) -> int: ...
2055    @overload
2056    def max_or_none(self: Stream[float]) -> float: ...
2057    def max_or_none(
2058        self: Union[Stream[int], Stream[float]],
2059    ) -> Union[float, int, None]:
2060        """
2061        Returns the maximum element of the given Stream.
2062
2063        Example 1:
2064        >>> lst = [1, 2, 3]
2065        >>> it(lst).max_or_none()
2066        3
2067
2068        Example 2:
2069        >>> lst = []
2070        >>> it(lst).max_or_none() is None
2071        True
2072        """
2073        return self.max_or_default(None)
2074
2075    @overload
2076    def min(self: Stream[int]) -> int:
2077        """
2078        Returns the minimum element of the given Stream.
2079
2080        Example 1:
2081        >>> lst = [1, 2, 3]
2082        >>> it(lst).min()
2083        1
2084        """
2085        ...
2086
2087    @overload
2088    def min(self: Stream[float]) -> float: ...
2089    def min(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2090        """
2091        Returns the minimum element of the given Stream.
2092
2093        Example 1:
2094        >>> lst = [1, 2, 3]
2095        >>> it(lst).min()
2096        1
2097        """
2098        return min(self)
2099
2100    @overload
2101    def min_or_none(self: Stream[int]) -> Optional[int]:
2102        """
2103        Returns the minimum element of the given Stream.
2104
2105        Example 1:
2106        >>> lst = [1, 2, 3]
2107        >>> it(lst).min_or_none()
2108        1
2109        """
2110        ...
2111
2112    @overload
2113    def min_or_none(self: Stream[float]) -> Optional[float]: ...
2114    def min_or_none(
2115        self: Union[Stream[int], Stream[float]],
2116    ) -> Union[float, int, None]:
2117        """
2118        Returns the minimum element of the given Stream.
2119
2120        Example 1:
2121        >>> lst = [1, 2, 3]
2122        >>> it(lst).min_or_none()
2123        1
2124        """
2125        return self.min_or_default(None)
2126
2127    @overload
2128    def min_or_default(self: Stream[int]) -> int:
2129        """
2130        Returns the minimum element of the given Stream.
2131
2132        Example 1:
2133        >>> lst = [1, 2, 3]
2134        >>> it(lst).min_or_default()
2135        1
2136        """
2137        ...
2138
2139    @overload
2140    def min_or_default(self: Stream[int], default: V) -> Union[int, V]: ...
2141    @overload
2142    def min_or_default(self: Stream[float]) -> float: ...
2143    @overload
2144    def min_or_default(self: Stream[float], default: V) -> Union[float, V]: ...
2145    def min_or_default(
2146        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2147    ) -> Union[float, int, V, None]:
2148        """
2149        Returns the minimum element of the given Stream.
2150
2151        Example 1:
2152        >>> lst = [1, 2, 3]
2153        >>> it(lst).min_or_default()
2154        1
2155
2156        Example 2:
2157        >>> lst = []
2158        >>> it(lst).min_or_default(9)
2159        9
2160        """
2161        if self.is_empty():
2162            return default
2163        return min(self)
2164
2165    @overload
2166    def mean(self: Stream[int]) -> float:
2167        """
2168        Returns the mean of the elements of the given Stream.
2169
2170        Example 1:
2171        >>> lst = [1, 2, 3]
2172        >>> it(lst).mean()
2173        2.0
2174        """
2175        ...
2176
2177    @overload
2178    def mean(self: Stream[float]) -> float: ...
2179    def mean(self: Union[Stream[int], Stream[float]]) -> float:
2180        """
2181        Returns the mean of the elements of the given Stream.
2182
2183        Example 1:
2184        >>> lst = [1, 2, 3]
2185        >>> it(lst).mean()
2186        2.0
2187        """
2188        return self.sum() / len(self)
2189
2190    # noinspection PyShadowingNames
2191    def reversed(self) -> Stream[T]:
2192        """
2193        Returns a list with elements in reversed order.
2194
2195        Example 1:
2196        >>> lst = ['b', 'c', 'a']
2197        >>> it(lst).reversed().to_list()
2198        ['a', 'c', 'b']
2199        """
2200        lst = list(self)
2201        lst.reverse()
2202        return it(lst)
2203
2204    @overload
2205    def flat_map(self, transform: Callable[[T], Iterable[U]]) -> Stream[U]: ...
2206    @overload
2207    def flat_map(self, transform: Callable[[T, int], Iterable[U]]) -> Stream[U]: ...
2208    @overload
2209    def flat_map(self, transform: Callable[[T, int, Stream[T]], Iterable[U]]) -> Stream[U]: ...
2210    def flat_map(self, transform: Callable[..., Iterable[U]]) -> Stream[U]:
2211        """
2212        Returns a single list of all elements yielded from results of [transform]
2213        function being invoked on each element of original collection.
2214
2215        Example 1:
2216        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2217        >>> it(lst).flat_map(lambda x: x).to_list()
2218        ['a', 'b', 'c', 'd', 'e']
2219        """
2220        return self.map(transform).flatten()
2221
2222    def flatten(self: Iterable[Iterable[U]]) -> Stream[U]:
2223        """
2224        Returns a sequence of all elements from all sequences in this sequence.
2225
2226        Example 1:
2227        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2228        >>> it(lst).flatten().to_list()
2229        ['a', 'b', 'c', 'd', 'e']
2230        """
2231        from .flattening import FlatteningTransform
2232
2233        return it(FlatteningTransform(self))
2234
2235    @overload
2236    def group_by(self, key_selector: Callable[[T], K]) -> Stream[Grouping[K, T]]: ...
2237    @overload
2238    def group_by(self, key_selector: Callable[[T, int], K]) -> Stream[Grouping[K, T]]: ...
2239    @overload
2240    def group_by(
2241        self, key_selector: Callable[[T, int, Stream[T]], K]
2242    ) -> Stream[Grouping[K, T]]: ...
2243    def group_by(self, key_selector: Callable[..., K]) -> Stream[Grouping[K, T]]:
2244        """
2245        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2246        and values being the corresponding elements of original collection.
2247
2248        Example 1:
2249        >>> lst = [1, 2, 3, 4, 5]
2250        >>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list()
2251        [(1, [1, 3, 5]), (0, [2, 4])]
2252        """
2253        from .grouping import GroupingTransform
2254
2255        return it(GroupingTransform(self, self.__callback_overload_warpper__(key_selector)))
2256
2257    @overload
2258    def group_by_to(
2259        self, destination: Dict[K, List[T]], key_selector: Callable[[T], K]
2260    ) -> Dict[K, List[T]]: ...
2261    @overload
2262    def group_by_to(
2263        self, destination: Dict[K, List[T]], key_selector: Callable[[T, int], K]
2264    ) -> Dict[K, List[T]]: ...
2265    @overload
2266    def group_by_to(
2267        self,
2268        destination: Dict[K, List[T]],
2269        key_selector: Callable[[T, int, Stream[T]], K],
2270    ) -> Dict[K, List[T]]: ...
2271    def group_by_to(
2272        self, destination: Dict[K, List[T]], key_selector: Callable[..., K]
2273    ) -> Dict[K, List[T]]:
2274        """
2275        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2276        and values being the corresponding elements of original collection.
2277
2278        Example 1:
2279        >>> lst = [1, 2, 3, 4, 5]
2280        >>> it(lst).group_by_to({}, lambda x: x%2)
2281        {1: [1, 3, 5], 0: [2, 4]}
2282        """
2283        key_selector = self.__callback_overload_warpper__(key_selector)
2284        for e in self:
2285            k = key_selector(e)
2286            if k not in destination:
2287                destination[k] = []
2288            destination[k].append(e)
2289        return destination
2290
2291    @overload
2292    def for_each(self, action: Callable[[T], None]) -> None: ...
2293    @overload
2294    def for_each(self, action: Callable[[T, int], None]) -> None: ...
2295    @overload
2296    def for_each(self, action: Callable[[T, int, Stream[T]], None]) -> None: ...
2297    def for_each(self, action: Callable[..., None]) -> None:
2298        """
2299        Invokes [action] function on each element of the given Stream.
2300
2301        Example 1:
2302        >>> lst = ['a', 'b', 'c']
2303        >>> it(lst).for_each(lambda x: print(x))
2304        a
2305        b
2306        c
2307
2308        Example 2:
2309        >>> lst = ['a', 'b', 'c']
2310        >>> it(lst).for_each(lambda x, i: print(x, i))
2311        a 0
2312        b 1
2313        c 2
2314        """
2315        self.on_each(action)
2316
2317    @overload
2318    def parallel_for_each(
2319        self, action: Callable[[T], None], max_workers: Optional[int] = None
2320    ) -> None: ...
2321    @overload
2322    def parallel_for_each(
2323        self, action: Callable[[T, int], None], max_workers: Optional[int] = None
2324    ) -> None: ...
2325    @overload
2326    def parallel_for_each(
2327        self,
2328        action: Callable[[T, int, Stream[T]], None],
2329        max_workers: Optional[int] = None,
2330    ) -> None: ...
2331    def parallel_for_each(
2332        self, action: Callable[..., None], max_workers: Optional[int] = None
2333    ) -> None:
2334        """
2335        Invokes [action] function on each element of the given Stream in parallel.
2336
2337        Example 1:
2338        >>> lst = ['a', 'b', 'c']
2339        >>> it(lst).parallel_for_each(lambda x: print(x))
2340        a
2341        b
2342        c
2343
2344        Example 2:
2345        >>> lst = ['a', 'b', 'c']
2346        >>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2)
2347        a
2348        b
2349        c
2350        """
2351        self.parallel_on_each(action, max_workers)
2352
2353    @overload
2354    def on_each(self, action: Callable[[T], None]) -> Stream[T]: ...
2355    @overload
2356    def on_each(self, action: Callable[[T, int], None]) -> Stream[T]: ...
2357    @overload
2358    def on_each(self, action: Callable[[T, int, Stream[T]], None]) -> Stream[T]: ...
2359    def on_each(self, action: Callable[..., None]) -> Stream[T]:
2360        """
2361        Invokes [action] function on each element of the given Stream.
2362
2363        Example 1:
2364        >>> lst = ['a', 'b', 'c']
2365        >>> it(lst).on_each(lambda x: print(x)) and None
2366        a
2367        b
2368        c
2369
2370        Example 2:
2371        >>> lst = ['a', 'b', 'c']
2372        >>> it(lst).on_each(lambda x, i: print(x, i)) and None
2373        a 0
2374        b 1
2375        c 2
2376        """
2377        action = self.__callback_overload_warpper__(action)
2378        for i in self:
2379            action(i)
2380        return self
2381
2382    @overload
2383    def parallel_on_each(
2384        self,
2385        action: Callable[[T], None],
2386        max_workers: Optional[int] = None,
2387        chunksize: int = 1,
2388        executor: "ParallelMappingTransform.Executor" = "Thread",
2389    ) -> Stream[T]: ...
2390    @overload
2391    def parallel_on_each(
2392        self,
2393        action: Callable[[T, int], None],
2394        max_workers: Optional[int] = None,
2395        chunksize: int = 1,
2396        executor: "ParallelMappingTransform.Executor" = "Thread",
2397    ) -> Stream[T]: ...
2398    @overload
2399    def parallel_on_each(
2400        self,
2401        action: Callable[[T, int, Stream[T]], None],
2402        max_workers: Optional[int] = None,
2403        chunksize: int = 1,
2404        executor: "ParallelMappingTransform.Executor" = "Thread",
2405    ) -> Stream[T]: ...
2406    def parallel_on_each(
2407        self,
2408        action: Callable[..., None],
2409        max_workers: Optional[int] = None,
2410        chunksize: int = 1,
2411        executor: "ParallelMappingTransform.Executor" = "Thread",
2412    ) -> Stream[T]:
2413        """
2414        Invokes [action] function on each element of the given Stream.
2415
2416        Example 1:
2417        >>> lst = ['a', 'b', 'c']
2418        >>> it(lst).parallel_on_each(lambda x: print(x)) and None
2419        a
2420        b
2421        c
2422
2423        Example 2:
2424        >>> lst = ['a', 'b', 'c']
2425        >>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None
2426        a
2427        b
2428        c
2429        """
2430        from .parallel_mapping import ParallelMappingTransform
2431
2432        action = self.__callback_overload_warpper__(action)
2433        for _ in ParallelMappingTransform(self, action, max_workers, chunksize, executor):
2434            pass
2435        return self
2436
2437    @overload
2438    def zip(self, other: Iterable[U]) -> Stream[Tuple[T, U]]: ...
2439    @overload
2440    def zip(self, other: Iterable[U], transform: Callable[[T, U], V]) -> Stream[V]: ...
2441    def zip(
2442        self,
2443        other: Iterable[Any],
2444        transform: Optional[Callable[..., V]] = None,  # type: ignore
2445    ) -> Stream[Any]:
2446        """
2447        Returns a new Stream of tuples, where each tuple contains two elements.
2448
2449        Example 1:
2450        >>> lst1 = ['a', 'b', 'c']
2451        >>> lst2 = [1, 2, 3]
2452        >>> it(lst1).zip(lst2).to_list()
2453        [('a', 1), ('b', 2), ('c', 3)]
2454
2455        Example 2:
2456        >>> lst1 = ['a', 'b', 'c']
2457        >>> lst2 = [1, 2, 3]
2458        >>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list()
2459        ['a__1', 'b__2', 'c__3']
2460        """
2461        if transform is None:
2462
2463            def transform(*x: Any) -> Tuple[Any, ...]:
2464                return (*x,)
2465
2466        from .merging import MergingTransform
2467
2468        return it(MergingTransform(self, other, transform))
2469
2470    @overload
2471    def zip_with_next(self) -> Stream[Tuple[T, T]]: ...
2472    @overload
2473    def zip_with_next(self, transform: Callable[[T, T], V]) -> Stream[V]: ...
2474    def zip_with_next(self, transform: Optional[Callable[[T, T], Any]] = None) -> Stream[Any]:
2475        """
2476        Returns a sequence containing the results of applying the given [transform] function
2477        to an each pair of two adjacent elements in this sequence.
2478
2479        Example 1:
2480        >>> lst = ['a', 'b', 'c']
2481        >>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list()
2482        ['a__b', 'b__c']
2483
2484        Example 2:
2485        >>> lst = ['a', 'b', 'c']
2486        >>> it(lst).zip_with_next().to_list()
2487        [('a', 'b'), ('b', 'c')]
2488        """
2489        from .merging_with_next import MergingWithNextTransform
2490
2491        return it(MergingWithNextTransform(self, transform or (lambda a, b: (a, b))))
2492
2493    @overload
2494    def unzip(self: Stream[Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ...
2495    @overload
2496    def unzip(self, transform: Callable[[T], Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ...
2497    @overload
2498    def unzip(
2499        self, transform: Callable[[T, int], Tuple[U, V]]
2500    ) -> "Tuple[ListLike[U], ListLike[V]]": ...
2501    @overload
2502    def unzip(
2503        self, transform: Callable[[T, int, Stream[T]], Tuple[U, V]]
2504    ) -> "Tuple[ListLike[U], ListLike[V]]": ...
2505    def unzip(  # type: ignore
2506        self: Stream[Tuple[U, V]],
2507        transform: Union[Optional[Callable[..., Tuple[Any, Any]]], bool] = None,
2508    ) -> "Tuple[ListLike[U], ListLike[V]]":
2509        """
2510        Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array.
2511
2512        Example 1:
2513        >>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}]
2514        >>> a, b = it(lst).unzip(lambda x: (x['name'], x['age']))
2515        >>> a
2516        ['a', 'b', 'c']
2517        >>> b
2518        [11, 12, 13]
2519
2520        Example 1:
2521        >>> lst = [('a', 11), ('b', 12), ('c', 13)]
2522        >>> a, b = it(lst).unzip()
2523        >>> a
2524        ['a', 'b', 'c']
2525        >>> b
2526        [11, 12, 13]
2527        """
2528        from .list_like import ListLike
2529
2530        it = self
2531        if isinstance(transform, bool):
2532            transform = None
2533
2534        if transform is not None:
2535            transform = self.__callback_overload_warpper__(transform)
2536            it = it.map(transform)
2537
2538        a = it.map(lambda x: x[0])  # type: ignore
2539        b = it.map(lambda x: x[1])  # type: ignore
2540
2541        return ListLike(a), ListLike(b)
2542
2543    def with_index(self) -> Stream[IndexedValue[T]]:
2544        """
2545        Returns a sequence containing the elements of this sequence and their indexes.
2546
2547        Example 1:
2548        >>> lst = ['a', 'b', 'c']
2549        >>> it(lst).with_index().to_list()
2550        [IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)]
2551        """
2552        return self.indexed()
2553
2554    @overload
2555    def shuffled(self) -> Stream[T]: ...
2556    @overload
2557    def shuffled(self, seed: Union[int, float, str, bytes, bytearray, None]) -> Stream[T]: ...
2558    @overload
2559    def shuffled(self, random: "Random") -> Stream[T]: ...
2560    def shuffled(  # type: ignore
2561        self, seed: Union["Random", int, float, str, bytes, bytearray, None] = None
2562    ) -> Stream[T]:
2563        """
2564        Returns a sequence that yields elements of this sequence randomly shuffled
2565        using the specified [random] instance as the source of randomness.
2566
2567        Example 1:
2568        >>> lst = ['a', 'b', 'c']
2569        >>> it(lst).shuffled('123').to_list()
2570        ['b', 'a', 'c']
2571
2572        Example 2:
2573        >>> from random import Random
2574        >>> lst = ['a', 'b', 'c']
2575        >>> it(lst).shuffled(Random('123')).to_list()
2576        ['b', 'a', 'c']
2577
2578        Example 3:
2579        >>> lst = ['a', 'b', 'c']
2580        >>> it(lst).shuffled(123).to_list()
2581        ['c', 'b', 'a']
2582        """
2583        from .shuffling import ShufflingTransform
2584
2585        return it(ShufflingTransform(self, seed))
2586
2587    @overload
2588    def partition(self, predicate: Callable[[T], bool]) -> "Tuple[ListLike[T], ListLike[T]]": ...
2589    @overload
2590    def partition(
2591        self, predicate: Callable[[T, int], bool]
2592    ) -> "Tuple[ListLike[T], ListLike[T]]": ...
2593    @overload
2594    def partition(
2595        self, predicate: Callable[[T, int, Stream[T]], bool]
2596    ) -> "Tuple[ListLike[T], ListLike[T]]": ...
2597    def partition(self, predicate: Callable[..., bool]) -> "Tuple[ListLike[T], ListLike[T]]":
2598        """
2599        Partitions the elements of the given Stream into two groups,
2600        the first group containing the elements for which the predicate returns true,
2601        and the second containing the rest.
2602
2603        Example 1:
2604        >>> lst = ['a', 'b', 'c', '2']
2605        >>> it(lst).partition(lambda x: x.isalpha())
2606        (['a', 'b', 'c'], ['2'])
2607
2608        Example 2:
2609        >>> lst = ['a', 'b', 'c', '2']
2610        >>> it(lst).partition(lambda _, i: i % 2 == 0)
2611        (['a', 'c'], ['b', '2'])
2612        """
2613        from .list_like import ListLike
2614
2615        predicate_a = self.__callback_overload_warpper__(predicate)
2616        predicate_b = self.__callback_overload_warpper__(predicate)
2617        part_a = self.filter(predicate_a)
2618        part_b = self.filter(lambda x: not predicate_b(x))
2619        return ListLike(part_a), ListLike(part_b)
2620
2621    def indexed(self) -> Stream[IndexedValue[T]]:
2622        return self.map(lambda x, i: IndexedValue(x, i))
2623
2624    @overload
2625    def combinations(self, n: Literal[2]) -> Stream[Tuple[T, T]]: ...
2626    @overload
2627    def combinations(self, n: Literal[3]) -> Stream[Tuple[T, T, T]]: ...
2628    @overload
2629    def combinations(self, n: Literal[4]) -> Stream[Tuple[T, T, T, T]]: ...
2630    @overload
2631    def combinations(self, n: Literal[5]) -> Stream[Tuple[T, T, T, T, T]]: ...
2632    def combinations(self, n: int) -> Stream[Tuple[T, ...]]:
2633        """
2634        Returns a Stream of all possible combinations of size [n] from the given Stream.
2635
2636        Example 1:
2637        >>> lst = ['a', 'b', 'c']
2638        >>> it(lst).combinations(2).to_list()
2639        [('a', 'b'), ('a', 'c'), ('b', 'c')]
2640        """
2641        from .combination import CombinationTransform
2642
2643        return it(CombinationTransform(self, n))
2644
2645    def nth(self, n: int) -> T:
2646        """
2647        Returns the nth element of the given Stream.
2648
2649        Example 1:
2650        >>> lst = ['a', 'b', 'c']
2651        >>> it(lst).nth(2)
2652        'c'
2653        """
2654        return self.skip(n).first()
2655
2656    def windowed(self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[List[T]]:
2657        """
2658         Returns a Stream of all possible sliding windows of size [size] from the given Stream.
2659
2660        Example 1:
2661        >>> lst = ['a', 'b', 'c', 'd', 'e']
2662        >>> it(lst).windowed(3).to_list()
2663        [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
2664
2665        Example 2:
2666        >>> lst = ['a', 'b', 'c', 'd', 'e']
2667        >>> it(lst).windowed(3, 2).to_list()
2668        [['a', 'b', 'c'], ['c', 'd', 'e']]
2669
2670        Example 3:
2671        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2672        >>> it(lst).windowed(3, 2, True).to_list()
2673        [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']]
2674        """
2675        from .windowed import WindowedTransform
2676
2677        return it(WindowedTransform(self, size, step, partialWindows))
2678
2679    def chunked(self, size: int) -> Stream[List[T]]:
2680        """
2681        Returns a Stream of all possible chunks of size [size] from the given Stream.
2682
2683        Example 1:
2684        >>> lst = ['a', 'b', 'c', 'd', 'e']
2685        >>> it(lst).chunked(3).to_list()
2686        [['a', 'b', 'c'], ['d', 'e']]
2687
2688
2689        Example 2:
2690        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2691        >>> it(lst).chunked(3).to_list()
2692        [['a', 'b', 'c'], ['d', 'e', 'f']]
2693        """
2694        return self.windowed(size, size, True)
2695
2696    def repeat(self, n: int) -> Stream[T]:
2697        """
2698        Returns a Stream containing this sequence repeated n times.
2699
2700        Example 1:
2701        >>> lst = ['a', 'b']
2702        >>> it(lst).repeat(3).to_list()
2703        ['a', 'b', 'a', 'b', 'a', 'b']
2704        """
2705        from .concat import ConcatTransform
2706
2707        return it(ConcatTransform([self] * n))
2708
2709    def concat(self, *other: Iterable[T]) -> Stream[T]:
2710        """
2711        Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream.
2712
2713        Example 1:
2714        >>> lst1 = ['a', 'b', 'c']
2715        >>> lst2 = [1, 2, 3]
2716        >>> it(lst1).concat(lst2).to_list()
2717        ['a', 'b', 'c', 1, 2, 3]
2718
2719        Example 2:
2720        >>> lst1 = ['a', 'b', 'c']
2721        >>> lst2 = [1, 2, 3]
2722        >>> lst3 = [4, 5, 6]
2723        >>> it(lst1).concat(lst2, lst3).to_list()
2724        ['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
2725        """
2726        from .concat import ConcatTransform
2727
2728        return it(ConcatTransform([self, *other]))
2729
2730    def intersect(self, *other: Iterable[T]) -> Stream[T]:
2731        """
2732        Returns a set containing all elements that are contained by both this collection and the specified collection.
2733
2734        The returned set preserves the element iteration order of the original collection.
2735
2736        To get a set containing all elements that are contained at least in one of these collections use union.
2737
2738        Example 1:
2739        >>> lst1 = ['a', 'b', 'c']
2740        >>> lst2 = ['a2', 'b2', 'c']
2741        >>> it(lst1).intersect(lst2).to_list()
2742        ['c']
2743
2744        Example 2:
2745        >>> lst1 = ['a', 'b', 'c']
2746        >>> lst2 = ['a2', 'b', 'c']
2747        >>> lst3 = ['a3', 'b', 'c3']
2748        >>> it(lst1).intersect(lst2, lst3).to_list()
2749        ['b']
2750
2751
2752        Example 1:
2753        >>> lst1 = ['a', 'a', 'c']
2754        >>> lst2 = ['a2', 'b2', 'a']
2755        >>> it(lst1).intersect(lst2).to_list()
2756        ['a']
2757        """
2758        from .intersection import IntersectionTransform
2759
2760        return it(IntersectionTransform([self, *other]))
2761
2762    def union(self, *other: Stream[T]) -> Stream[T]:
2763        """
2764        Returns a set containing all distinct elements from both collections.
2765
2766        The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.
2767
2768        To get a set containing all elements that are contained in both collections use intersect.
2769
2770        Example 1:
2771        >>> lst1 = ['a', 'b', 'c']
2772        >>> lst2 = ['a2', 'b2', 'c']
2773        >>> it(lst1).union(lst2).to_list()
2774        ['a', 'b', 'c', 'a2', 'b2']
2775
2776        Example 2:
2777        >>> lst1 = ['a', 'b', 'c']
2778        >>> lst2 = ['a2', 'b', 'c']
2779        >>> lst3 = ['a3', 'b', 'c3']
2780        >>> it(lst1).union(lst2, lst3).to_list()
2781        ['a', 'b', 'c', 'a2', 'a3', 'c3']
2782
2783
2784        Example 1:
2785        >>> lst1 = ['a', 'a', 'c']
2786        >>> lst2 = ['a2', 'b2', 'a']
2787        >>> it(lst1).union(lst2).to_list()
2788        ['a', 'c', 'a2', 'b2']
2789        """
2790        return self.concat(*other).distinct()
2791
2792    def join(self: Stream[str], separator: str = " ") -> str:
2793        """
2794        Joins the elements of the given Stream into a string.
2795
2796        Example 1:
2797        >>> lst = ['a', 'b', 'c']
2798        >>> it(lst).join(', ')
2799        'a, b, c'
2800        """
2801        return separator.join(self)
2802
2803    @overload
2804    def progress(self) -> Stream[T]: ...
2805    @overload
2806    def progress(
2807        self, progress_func: Union[Literal["tqdm"], Literal["tqdm_rich"]]
2808    ) -> Stream[T]: ...
2809    @overload
2810    def progress(self, progress_func: Callable[[Stream[T]], Iterable[T]]) -> Stream[T]: ...
2811    def progress(
2812        self,
2813        progress_func: Union[
2814            Callable[[Stream[T]], Iterable[T]],
2815            Literal["tqdm"],
2816            Literal["tqdm_rich"],
2817            None,
2818        ] = None,
2819    ) -> Stream[T]:
2820        """
2821        Returns a Stream that enable a progress bar for the given Stream.
2822
2823        Example 1:
2824        >>> from tqdm import tqdm
2825        >>> from time import sleep
2826        >>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None
2827        >>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass
2828        """
2829        if progress_func is not None and callable(progress_func):
2830            return it(progress_func(self))
2831
2832        def import_tqdm():
2833            if progress_func == "tqdm_rich":
2834                import warnings
2835                from tqdm.rich import tqdm
2836                from tqdm import TqdmExperimentalWarning
2837
2838                warnings.filterwarnings("ignore", category=TqdmExperimentalWarning)
2839            else:
2840                from tqdm import tqdm
2841            return tqdm
2842
2843        try:
2844            tqdm = import_tqdm()
2845        except ImportError:
2846            from pip import main as pip  # type: ignore
2847
2848            pip(["install", "tqdm"])
2849            tqdm = import_tqdm()
2850
2851        return it(tqdm(self, total=len(self)))
2852
2853    def typing_as(self, typ: Type[U]) -> Stream[U]:
2854        """
2855        Cast the element as specific Type to gain code completion base on type annotations.
2856        """
2857        el = self.first_not_none_of_or_none()
2858        if el is None or isinstance(el, typ) or not isinstance(el, dict):
2859            return self  # type: ignore
2860
2861        class AttrDict(Dict[str, Any]):
2862            def __init__(self, value: Dict[str, Any]) -> None:
2863                super().__init__(**value)
2864                setattr(self, "__dict__", value)
2865                self.__getattr__ = value.__getitem__
2866                self.__setattr__ = value.__setattr__  # type: ignore
2867
2868        return self.map(AttrDict)  # type: ignore  # use https://github.com/cdgriffith/Box ?
2869
2870    def to_set(self) -> Set[T]:
2871        """
2872        Returns a set containing all elements of this Stream.
2873
2874        Example 1:
2875        >>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'}
2876        True
2877        """
2878        return set(self)
2879
2880    @overload
2881    def to_dict(self: Stream[Tuple[K, V]]) -> Dict[K, V]: ...
2882    @overload
2883    def to_dict(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ...
2884    @overload
2885    def to_dict(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ...
2886    @overload
2887    def to_dict(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ...
2888    def to_dict(self, transform: Optional[Callable[..., Tuple[K, V]]] = None) -> Dict[K, V]:
2889        """
2890        Returns a [Dict] containing key-value Tuple provided by [transform] function
2891        applied to elements of the given Stream.
2892
2893        Example 1:
2894        >>> lst = ['1', '2', '3']
2895        >>> it(lst).to_dict(lambda x: (int(x), x))
2896        {1: '1', 2: '2', 3: '3'}
2897
2898        Example 2:
2899        >>> lst = [(1, '1'), (2, '2'), (3, '3')]
2900        >>> it(lst).to_dict()
2901        {1: '1', 2: '2', 3: '3'}
2902        """
2903        return self.associate(transform or (lambda x: x))  # type: ignore
2904
2905    def to_list(self) -> List[T]:
2906        """
2907        Returns a list with elements of the given Stream.
2908
2909        Example 1:
2910        >>> it(['b', 'c', 'a']).to_list()
2911        ['b', 'c', 'a']
2912        """
2913        if self.__transform__.cache is not None:
2914            return self.__transform__.cache.copy()
2915        return [s for s in self]
2916
2917    async def to_list_async(self: Iterable[Awaitable[T]]) -> List[T]:
2918        """
2919        Returns a list with elements of the given Stream.
2920
2921        Example 1:
2922        >>> it(['b', 'c', 'a']).to_list()
2923        ['b', 'c', 'a']
2924        """
2925        from asyncio import gather
2926
2927        return await gather(*self)  # type: ignore
2928
2929    def let(self, block: Callable[[Stream[T]], U]) -> U:
2930        """
2931        Calls the specified function [block] with `self` value as its argument and returns its result.
2932
2933        Example 1:
2934        >>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list()
2935        ['a!', 'b!', 'c!']
2936        """
2937        return block(self)
2938
2939    def also(self, block: Callable[[Stream[T]], Any]) -> Stream[T]:
2940        """
2941        Calls the specified function [block] with `self` value as its argument and returns `self` value.
2942
2943        Example 1:
2944        >>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list()
2945        ['a', 'b', 'c']
2946        """
2947        block(self)
2948        return self
2949
2950    @property
2951    def size(self) -> int:
2952        """
2953        Returns the size of the given Stream.
2954        """
2955        return len(self.data)
2956
2957    def is_empty(self) -> bool:
2958        """
2959        Returns True if the Stream is empty, False otherwise.
2960
2961        Example 1:
2962        >>> it(['a', 'b', 'c']).is_empty()
2963        False
2964
2965        Example 2:
2966        >>> it([None]).is_empty()
2967        False
2968
2969        Example 3:
2970        >>> it([]).is_empty()
2971        True
2972        """
2973        return id(self.first_or_default(self)) == id(self)
2974
2975    def __iter__(self) -> Iterator[T]:
2976        return self.__do_iter__()
2977
2978    def iter(self) -> Iterator[T]:
2979        return self.__do_iter__()
2980
2981    def __do_iter__(self) -> Iterator[T]:
2982        yield from self.__transform__
2983
2984    def __len__(self) -> int:
2985        return len(self.__transform__)
2986
2987    def __bool__(self) -> bool:
2988        return not self.is_empty()
2989
2990    def __repr__(self) -> str:
2991        if self.__transform__.cache is None:
2992            return "[...]"
2993        return repr(self.to_list())
2994
2995    def __getitem__(self, key: int) -> T:
2996        """
2997        Returns the element at the specified [index] in the Stream.
2998
2999        Example 1:
3000        >>> lst = [1, 2, 3]
3001        >>> it(lst)[1]
3002        2
3003
3004        Example 2:
3005        >>> lst = [1, 2, 3]
3006        >>> it(lst)[3]
3007        Traceback (most recent call last):
3008        ...
3009        IndexError: Index 3 out of range
3010        """
3011        return self.element_at(key)
3012
3013    @overload
3014    def __callback_overload_warpper__(self, callback: Callable[[T], U]) -> Callable[[T], U]: ...
3015    @overload
3016    def __callback_overload_warpper__(
3017        self, callback: Callable[[T, int], U]
3018    ) -> Callable[[T], U]: ...
3019    @overload
3020    def __callback_overload_warpper__(
3021        self, callback: Callable[[T, int, Stream[T]], U]
3022    ) -> Callable[[T], U]: ...
3023    def __callback_overload_warpper__(self, callback: Callable[..., U]) -> Callable[[T], U]:
3024        if hasattr(callback, "__code__"):
3025            if callback.__code__.co_argcount == 2:
3026                index = AutoIncrementIndex()
3027                return lambda x: callback(x, index())
3028            if callback.__code__.co_argcount == 3:
3029                index = AutoIncrementIndex()
3030                return lambda x: callback(x, index(), self)
3031        return callback
3032
3033
3034class AutoIncrementIndex:
3035    idx = 0
3036
3037    def __call__(self) -> int:
3038        val = self.idx
3039        self.idx += 1
3040        return val
3041
3042
3043class IndexedValue(NamedTuple, Generic[T]):
3044    val: T
3045    idx: int
3046
3047    def __repr__(self) -> str:
3048        return f"IndexedValue({self.idx}, {self.val})"
3049
3050
3051def throw(exception: Exception) -> Any:
3052    raise exception
3053
3054
3055def none_or(value: Optional[T], default: T) -> T:
3056    return value if value is not None else default
3057
3058
3059def none_or_else(value: Optional[T], f: Callable[[], T]) -> T:
3060    return value if value is not None else f()
3061
3062
3063def is_debugging() -> bool:
3064    from inspect import currentframe
3065    from traceback import walk_stack
3066
3067    return (
3068        it(walk_stack(currentframe()))
3069        .take(20)
3070        .map(lambda s: s[0])
3071        .any(
3072            lambda s: (
3073                s.f_code.co_name == "get_contents_debug_adapter_protocol"
3074                and "pydevd_resolver.py" in s.f_code.co_filename
3075            )
3076        )
3077    )
3078
3079
3080class StreamProducer:
3081    @overload
3082    def __call__(self, elements: List[T]) -> Stream[T]: ...
3083    @overload
3084    def __call__(self, elements: Iterable[T]) -> Stream[T]: ...
3085    @overload
3086    def __call__(self, *elements: T) -> Stream[T]: ...
3087    def __call__(self, *iterable: Union[Iterable[T], List[T], T]) -> Stream[T]:  # type: ignore
3088        if len(iterable) == 1:
3089            iter = iterable[0]
3090            if isinstance(iter, Stream):
3091                return iter  # type: ignore
3092            if isinstance(iter, Iterable) and not isinstance(iter, str):
3093                return Stream(iter)  # type: ignore
3094        return Stream(iterable)  # type: ignore
3095
3096    def json(self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[Any]:
3097        """
3098        Reads and parses the input of a json file.
3099        """
3100        import json
3101
3102        with open(filepath, "r") as f:
3103            data = json.load(f, **kwargs)  # type: ignore
3104            return self(data)
3105
3106    def csv(self, filepath: str) -> Stream[List[str]] | Stream[Dict[str, str]]:
3107        """
3108        Reads and parses the input of a csv file.
3109        """
3110        return self.read_csv(filepath)
3111
3112    def read_csv(
3113        self, filepath: str, header: Optional[int] = 0
3114    ) -> Stream[List[str]] | Stream[Dict[str, str]]:
3115        """
3116        Reads and parses the input of a csv file.
3117
3118        Example 1:
3119        >>> it.read_csv('tests/data/a.csv').to_list()
3120        [{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}]
3121        """
3122        import csv
3123
3124        it = self
3125        with open(filepath) as f:
3126            reader = csv.reader(f)
3127            iter = it(*reader)
3128            if header is None or header < 0:
3129                return iter
3130
3131            headers = iter.element_at_or_none(header)
3132            if headers is not None:
3133                if header == 0:
3134                    iter = iter.skip(1)
3135                else:
3136                    iter = iter.filter(lambda _, i: i != header)
3137
3138                return iter.map(
3139                    lambda row: it(row).associate_by(
3140                        lambda _, ordinal: (
3141                            headers[ordinal] if ordinal < len(headers) else f"undefined_{ordinal}"
3142                        )
3143                    )
3144                )
3145            return iter
3146
3147    def __repr__(self) -> str:
3148        return __package__ or self.__class__.__name__
3149
3150
3151it: StreamProducer = StreamProducer()
3152"""
3153    Creates an iterator from a list of elements or given Iterable.
3154
3155    Example 1:
3156>>> it('hello', 'world').map(lambda x: x.upper()).to_list()
3157['HELLO', 'WORLD']
3158
3159    Example 2:
3160>>> it(['hello', 'world']).map(lambda x: x.upper()).to_list()
3161['HELLO', 'WORLD']
3162
3163    Example 3:
3164>>> it(range(10)).map(lambda x: x*x).to_list()
3165[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3166"""
3167
3168
3169if __name__ == "__main__":
3170    import doctest
3171
3172    doctest.testmod()
class Stream(typing.Generic[~T], typing.Iterable[~T]):
  50class Stream(Generic[T], Iterable[T]):
  51    """
  52    Given an [iterator] function constructs a [Stream] that returns values through the [Iterator]
  53    provided by that function.
  54
  55    The values are evaluated lazily, and the sequence is potentially infinite.
  56    """
  57
  58    __transform__: Transform[Any, T]
  59
  60    def __init__(self, iterable: Union[Iterable[T], Transform[Any, T]]) -> None:
  61        super().__init__()
  62
  63        self.__transform__ = new_transform(iterable)
  64
  65    @cached_property
  66    def transforms(self) -> Iterable[Transform[Any, Any]]:
  67        return [*self.__transform__.transforms()]
  68
  69    @property
  70    def data(self) -> List[T]:
  71        if self.__transform__.cache is not None:
  72            return self.__transform__.cache.copy()
  73        if is_debugging():
  74            raise LazyEvaluationException("The sequence has not been evaluated yet.")
  75        return self.to_list()
  76
  77    def dedup(self) -> Stream[T]:
  78        """
  79        Removes consecutive repeated elements in the sequence.
  80
  81        If the sequence is sorted, this removes all duplicates.
  82
  83        Example 1:
  84        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
  85        >>> it(lst).dedup().to_list()
  86        ['a1', 'b2', 'a2', 'a1']
  87
  88        Example 1:
  89        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
  90        >>> it(lst).sorted().dedup().to_list()
  91        ['a1', 'a2', 'b2']
  92        """
  93        return self.dedup_by(lambda x: x)
  94
  95    @overload
  96    def dedup_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ...
  97    @overload
  98    def dedup_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ...
  99    @overload
 100    def dedup_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ...
 101    def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
 102        """
 103        Removes all but the first of consecutive elements in the sequence that resolve to the same key.
 104        """
 105        return self.dedup_into_group_by(key_selector).map(lambda x: x[0])
 106
 107    @overload
 108    def dedup_with_count_by(self, key_selector: Callable[[T], Any]) -> Stream[Tuple[T, int]]: ...
 109    @overload
 110    def dedup_with_count_by(
 111        self, key_selector: Callable[[T, int], Any]
 112    ) -> Stream[Tuple[T, int]]: ...
 113    @overload
 114    def dedup_with_count_by(
 115        self, key_selector: Callable[[T, int, Stream[T]], Any]
 116    ) -> Stream[Tuple[T, int]]: ...
 117    def dedup_with_count_by(self, key_selector: Callable[..., Any]) -> Stream[Tuple[T, int]]:
 118        """
 119        Removes all but the first of consecutive elements and its count that resolve to the same key.
 120
 121        Example 1:
 122        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
 123        >>> it(lst).dedup_with_count_by(lambda x: x).to_list()
 124        [('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)]
 125
 126        Example 1:
 127        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
 128        >>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list()
 129        [('a1', 3), ('a2', 1), ('b2', 1)]
 130        """
 131        return self.dedup_into_group_by(key_selector).map(lambda x: (x[0], len(x)))
 132
 133    @overload
 134    def dedup_into_group_by(self, key_selector: Callable[[T], Any]) -> Stream[List[T]]: ...
 135    @overload
 136    def dedup_into_group_by(self, key_selector: Callable[[T, int], Any]) -> Stream[List[T]]: ...
 137    @overload
 138    def dedup_into_group_by(
 139        self, key_selector: Callable[[T, int, Stream[T]], Any]
 140    ) -> Stream[List[T]]: ...
 141    def dedup_into_group_by(self, key_selector: Callable[..., Any]) -> Stream[List[T]]:
 142        from .dedup import DedupTransform
 143
 144        return it(DedupTransform(self, key_selector))
 145
 146    @overload
 147    def filter(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
 148    @overload
 149    def filter(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
 150    @overload
 151    def filter(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
 152    def filter(self, predicate: Callable[..., bool]) -> Stream[T]:
 153        """
 154        Returns a Stream containing only elements matching the given [predicate].
 155
 156        Example 1:
 157        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 158        >>> it(lst).filter(lambda x: x.startswith('a')).to_list()
 159        ['a1', 'a2']
 160
 161        Example 2:
 162        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 163        >>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list()
 164        ['a1', 'b2', 'a2']
 165        """
 166        from .filtering import FilteringTransform
 167
 168        return it(FilteringTransform(self, self.__callback_overload_warpper__(predicate)))
 169
 170    def filter_is_instance(self, typ: Type[U]) -> Stream[U]:
 171        """
 172        Returns a Stream containing all elements that are instances of specified type parameter typ.
 173
 174        Example 1:
 175        >>> lst = [ 'a1', 1, 'b2', 3]
 176        >>> it(lst).filter_is_instance(int).to_list()
 177        [1, 3]
 178
 179        """
 180        from .type_guard import TypeGuardTransform, TypeGuard
 181
 182        def guard(x: T) -> TypeGuard[U]:
 183            return isinstance(x, typ)
 184
 185        return it(TypeGuardTransform(self, guard))
 186
 187    @overload
 188    def filter_not(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
 189    @overload
 190    def filter_not(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
 191    @overload
 192    def filter_not(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
 193    def filter_not(self, predicate: Callable[..., bool]) -> Stream[T]:
 194        """
 195        Returns a Stream containing all elements not matching the given [predicate].
 196
 197        Example 1:
 198        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
 199        >>> it(lst).filter_not(lambda x: x.startswith('a')).to_list()
 200        ['b1', 'b2']
 201
 202        Example 2:
 203        >>> lst = [ 'a1', 'a2', 'b1', 'b2']
 204        >>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list()
 205        ['a2', 'b1', 'b2']
 206        """
 207        predicate = self.__callback_overload_warpper__(predicate)
 208        return self.filter(lambda x: not predicate(x))
 209
 210    @overload
 211    def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]: ...
 212    @overload
 213    def filter_not_none(self: Stream[T]) -> Stream[T]: ...
 214    def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]:
 215        """
 216        Returns a Stream containing all elements that are not `None`.
 217
 218        Example 1:
 219        >>> lst = [ 'a', None, 'b']
 220        >>> it(lst).filter_not_none().to_list()
 221        ['a', 'b']
 222        """
 223        from .type_guard import TypeGuardTransform, TypeGuard
 224
 225        def guard(x: Optional[U]) -> TypeGuard[U]:
 226            return x is not None
 227
 228        return it(TypeGuardTransform(self, guard))
 229
 230    @overload
 231    def map(self, transform: Callable[[T], U]) -> Stream[U]: ...
 232    @overload
 233    def map(self, transform: Callable[[T], U], return_exceptions: Literal[False]) -> Stream[U]: ...
 234    @overload
 235    def map(
 236        self, transform: Callable[[T], U], return_exceptions: Literal[True]
 237    ) -> Stream[Union[U, BaseException]]: ...
 238    @overload
 239    def map(self, transform: Callable[[T, int], U]) -> Stream[U]: ...
 240    @overload
 241    def map(
 242        self, transform: Callable[[T, int], U], return_exceptions: Literal[False]
 243    ) -> Stream[U]: ...
 244    @overload
 245    def map(
 246        self, transform: Callable[[T, int], U], return_exceptions: Literal[True]
 247    ) -> Stream[Union[U, BaseException]]: ...
 248    @overload
 249    def map(self, transform: Callable[[T, int, Stream[T]], U]) -> Stream[U]: ...
 250    @overload
 251    def map(
 252        self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[False]
 253    ) -> Stream[U]: ...
 254    @overload
 255    def map(
 256        self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[True]
 257    ) -> Stream[Union[U, BaseException]]: ...
 258    def map(
 259        self, transform: Callable[..., U], return_exceptions: bool = False
 260    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
 261        """
 262        Returns a Stream containing the results of applying the given [transform] function
 263        to each element in the original Stream.
 264
 265        Example 1:
 266        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 267        >>> it(lst).map(lambda x: x['age']).to_list()
 268        [12, 13]
 269
 270        Example 2:
 271        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 272        >>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list()
 273        ['A0', 'B1']
 274
 275        Example 3:
 276        >>> lst = ['hi', 'abc']
 277        >>> it(lst).map(len).to_list()
 278        [2, 3]
 279        """
 280        from .mapping import MappingTransform
 281
 282        transform = self.__callback_overload_warpper__(transform)
 283        if return_exceptions:
 284
 285            def transform_wrapper(x: T) -> Union[U, BaseException]:
 286                try:
 287                    return transform(x)
 288                except BaseException as e:
 289                    return e
 290
 291            return it(MappingTransform(self, transform_wrapper))
 292
 293        return it(MappingTransform(self, transform))
 294
 295    @overload
 296    async def map_async(self, transform: Callable[[T], Awaitable[U]]) -> Stream[U]: ...
 297    @overload
 298    async def map_async(
 299        self,
 300        transform: Callable[[T, int], Awaitable[U]],
 301        return_exceptions: Literal[True],
 302    ) -> Stream[Union[U, BaseException]]: ...
 303    @overload
 304    async def map_async(
 305        self,
 306        transform: Callable[[T, int, Stream[T]], Awaitable[U]],
 307        return_exceptions: Literal[False] = False,
 308    ) -> Stream[U]: ...
 309    async def map_async(
 310        self, transform: Callable[..., Awaitable[U]], return_exceptions: bool = False
 311    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
 312        """
 313        Similar to `.map()` but you can input a async transform then await it.
 314        """
 315        from asyncio import gather
 316
 317        if return_exceptions:
 318            return it(await gather(*self.map(transform), return_exceptions=True))
 319        return it(await gather(*self.map(transform)))
 320
 321    @overload
 322    def map_not_none(self, transform: Callable[[T], Optional[U]]) -> Stream[U]: ...
 323    @overload
 324    def map_not_none(self, transform: Callable[[T, int], Optional[U]]) -> Stream[U]: ...
 325    @overload
 326    def map_not_none(self, transform: Callable[[T, int, Stream[T]], Optional[U]]) -> Stream[U]: ...
 327    def map_not_none(self, transform: Callable[..., Optional[U]]) -> Stream[U]:
 328        """
 329        Returns a Stream containing only the non-none results of applying the given [transform] function
 330        to each element in the original collection.
 331
 332        Example 1:
 333        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}]
 334        >>> it(lst).map_not_none(lambda x: x['age']).to_list()
 335        [12]
 336        """
 337        return self.map(transform).filter_not_none()  # type: ignore
 338
 339    @overload
 340    def parallel_map(
 341        self,
 342        transform: Callable[[T], U],
 343        max_workers: Optional[int] = None,
 344        chunksize: int = 1,
 345        executor: ParallelMappingTransform.Executor = "Thread",
 346    ) -> Stream[U]: ...
 347    @overload
 348    def parallel_map(
 349        self,
 350        transform: Callable[[T, int], U],
 351        max_workers: Optional[int] = None,
 352        chunksize: int = 1,
 353        executor: ParallelMappingTransform.Executor = "Thread",
 354    ) -> Stream[U]: ...
 355    @overload
 356    def parallel_map(
 357        self,
 358        transform: Callable[[T, int, Stream[T]], U],
 359        max_workers: Optional[int] = None,
 360        chunksize: int = 1,
 361        executor: ParallelMappingTransform.Executor = "Thread",
 362    ) -> Stream[U]: ...
 363    def parallel_map(
 364        self,
 365        transform: Callable[..., U],
 366        max_workers: Optional[int] = None,
 367        chunksize: int = 1,
 368        executor: ParallelMappingTransform.Executor = "Thread",
 369    ) -> Stream[U]:
 370        """
 371        Returns a Stream containing the results of applying the given [transform] function
 372        to each element in the original Stream.
 373
 374        Example 1:
 375        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 376        >>> it(lst).parallel_map(lambda x: x['age']).to_list()
 377        [12, 13]
 378
 379        Example 2:
 380        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 381        >>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list()
 382        [12, 13]
 383
 384        Example 3:
 385        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
 386        >>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list()
 387        [12, 14]
 388        """
 389        from .parallel_mapping import ParallelMappingTransform
 390
 391        return it(
 392            ParallelMappingTransform(
 393                self,
 394                self.__callback_overload_warpper__(transform),
 395                max_workers,
 396                chunksize,
 397                executor,
 398            )
 399        )
 400
 401    @overload
 402    def find(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 403    @overload
 404    def find(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 405    @overload
 406    def find(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 407    def find(self, predicate: Callable[..., bool]) -> Optional[T]:
 408        """
 409        Returns the first element matching the given [predicate], or `None` if no such element was found.
 410
 411        Example 1:
 412        >>> lst = ['a', 'b', 'c']
 413        >>> it(lst).find(lambda x: x == 'b')
 414        'b'
 415        """
 416        return self.first_or_none(predicate)
 417
 418    def find_last(self, predicate: Callable[[T], bool]) -> Optional[T]:
 419        """
 420        Returns the last element matching the given [predicate], or `None` if no such element was found.
 421
 422        Example 1:
 423        >>> lst = ['a', 'b', 'c']
 424        >>> it(lst).find_last(lambda x: x == 'b')
 425        'b'
 426        """
 427        return self.last_or_none(predicate)
 428
 429    @overload
 430    def first(self) -> T: ...
 431    @overload
 432    def first(self, predicate: Callable[[T], bool]) -> T: ...
 433    @overload
 434    def first(self, predicate: Callable[[T, int], bool]) -> T: ...
 435    @overload
 436    def first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
 437    def first(self, predicate: Optional[Callable[..., bool]] = None) -> T:
 438        """
 439        Returns first element.
 440
 441        Example 1:
 442        >>> lst = ['a', 'b', 'c']
 443        >>> it(lst).first()
 444        'a'
 445
 446        Example 2:
 447        >>> lst = []
 448        >>> it(lst).first()
 449        Traceback (most recent call last):
 450        ...
 451        ValueError: Stream is empty.
 452
 453        Example 3:
 454        >>> lst = ['a', 'b', 'c']
 455        >>> it(lst).first(lambda x: x == 'b')
 456        'b'
 457
 458        Example 4:
 459        >>> lst = ['a', 'b', 'c']
 460        >>> it(lst).first(lambda x: x == 'd')
 461        Traceback (most recent call last):
 462        ...
 463        ValueError: Stream is empty.
 464
 465        Example 5:
 466        >>> lst = [None]
 467        >>> it(lst).first() is None
 468        True
 469        """
 470        for e in self:
 471            if predicate is None or predicate(e):
 472                return e
 473        raise ValueError("Stream is empty.")
 474
 475    @overload
 476    def first_not_none_of(self: Stream[Optional[U]]) -> U: ...
 477    @overload
 478    def first_not_none_of(
 479        self: Stream[Optional[U]], transform: Callable[[Optional[U]], Optional[U]]
 480    ) -> U: ...
 481    @overload
 482    def first_not_none_of(
 483        self: Stream[Optional[U]],
 484        transform: Callable[[Optional[U], int], Optional[U]],
 485    ) -> U: ...
 486    @overload
 487    def first_not_none_of(
 488        self: Stream[Optional[U]],
 489        transform: Callable[[Optional[U], int, Stream[Optional[U]]], Optional[U]],
 490    ) -> U: ...
 491    def first_not_none_of(
 492        self: Stream[Optional[U]],
 493        transform: Optional[Callable[..., Optional[U]]] = None,
 494    ) -> U:
 495        """
 496        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
 497
 498        Example 1:
 499        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
 500        >>> it(lst).first_not_none_of(lambda x: x['age'])
 501        12
 502
 503        Example 2:
 504        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
 505        >>> it(lst).first_not_none_of(lambda x: x['age'])
 506        Traceback (most recent call last):
 507        ...
 508        ValueError: No element of the Stream was transformed to a non-none value.
 509        """
 510
 511        v = (
 512            self.first_not_none_of_or_none()
 513            if transform is None
 514            else self.first_not_none_of_or_none(transform)
 515        )
 516        if v is None:
 517            raise ValueError("No element of the Stream was transformed to a non-none value.")
 518        return v
 519
 520    @overload
 521    def first_not_none_of_or_none(self) -> Optional[T]: ...
 522    @overload
 523    def first_not_none_of_or_none(self, transform: Callable[[T], T]) -> Optional[T]: ...
 524    @overload
 525    def first_not_none_of_or_none(self, transform: Callable[[T, int], T]) -> Optional[T]: ...
 526    @overload
 527    def first_not_none_of_or_none(
 528        self, transform: Callable[[T, int, Stream[T]], T]
 529    ) -> Optional[T]: ...
 530    def first_not_none_of_or_none(
 531        self, transform: Optional[Callable[..., T]] = None
 532    ) -> Optional[T]:
 533        """
 534        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
 535
 536        Example 1:
 537        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
 538        >>> it(lst).first_not_none_of_or_none(lambda x: x['age'])
 539        12
 540
 541        Example 2:
 542        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
 543        >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None
 544        True
 545        """
 546        if transform is None:
 547            return self.first_or_none()
 548        return self.map_not_none(transform).first_or_none()
 549
 550    @overload
 551    def first_or_none(self) -> Optional[T]: ...
 552    @overload
 553    def first_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 554    @overload
 555    def first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 556    @overload
 557    def first_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 558    def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
 559        """
 560        Returns the first element, or `None` if the Stream is empty.
 561
 562        Example 1:
 563        >>> lst = []
 564        >>> it(lst).first_or_none() is None
 565        True
 566
 567        Example 2:
 568        >>> lst = ['a', 'b', 'c']
 569        >>> it(lst).first_or_none()
 570        'a'
 571
 572        Example 2:
 573        >>> lst = ['a', 'b', 'c']
 574        >>> it(lst).first_or_none(lambda x: x == 'b')
 575        'b'
 576        """
 577        if predicate is not None:
 578            return self.first_or_default(predicate, None)
 579        else:
 580            return self.first_or_default(None)
 581
 582    @overload
 583    def first_or_default(self, default: U) -> Union[T, U]: ...
 584    @overload
 585    def first_or_default(self, predicate: Callable[[T], bool], default: U) -> Union[T, U]: ...
 586    @overload
 587    def first_or_default(self, predicate: Callable[[T, int], bool], default: U) -> Union[T, U]: ...
 588    @overload
 589    def first_or_default(
 590        self, predicate: Callable[[T, int, Stream[T]], bool], default: U
 591    ) -> Union[T, U]: ...
 592    def first_or_default(  # type: ignore
 593        self, predicate: Union[Callable[..., bool], U], default: Optional[U] = None
 594    ) -> Union[T, U, None]:
 595        """
 596        Returns the first element, or the given [default] if the Stream is empty.
 597
 598        Example 1:
 599        >>> lst = []
 600        >>> it(lst).first_or_default('a')
 601        'a'
 602
 603        Example 2:
 604        >>> lst = ['b']
 605        >>> it(lst).first_or_default('a')
 606        'b'
 607
 608        Example 3:
 609        >>> lst = ['a', 'b', 'c']
 610        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
 611        'b'
 612
 613        Example 4:
 614        >>> lst = []
 615        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
 616        'd'
 617        """
 618        seq = self
 619        if isinstance(predicate, Callable):
 620            seq = self.filter(predicate)  # type: ignore
 621        else:
 622            default = predicate
 623        return next(iter(seq), default)
 624
 625    @overload
 626    def last(self) -> T: ...
 627    @overload
 628    def last(self, predicate: Callable[[T], bool]) -> T: ...
 629    @overload
 630    def last(self, predicate: Callable[[T, int], bool]) -> T: ...
 631    @overload
 632    def last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
 633    def last(self, predicate: Optional[Callable[..., bool]] = None) -> T:
 634        """
 635        Returns last element.
 636
 637        Example 1:
 638        >>> lst = ['a', 'b', 'c']
 639        >>> it(lst).last()
 640        'c'
 641
 642        Example 2:
 643        >>> lst = []
 644        >>> it(lst).last()
 645        Traceback (most recent call last):
 646        ...
 647        ValueError: Stream is empty.
 648        """
 649        v = self.last_or_none(predicate) if predicate is not None else self.last_or_none()
 650        if v is None:
 651            raise ValueError("Stream is empty.")
 652        return v
 653
 654    @overload
 655    def last_or_none(self) -> Optional[T]: ...
 656    @overload
 657    def last_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
 658    @overload
 659    def last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
 660    @overload
 661    def last_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
 662    def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
 663        """
 664        Returns the last element matching the given [predicate], or `None` if no such element was found.
 665
 666        Exmaple 1:
 667        >>> lst = ['a', 'b', 'c']
 668        >>> it(lst).last_or_none()
 669        'c'
 670
 671        Exmaple 2:
 672        >>> lst = ['a', 'b', 'c']
 673        >>> it(lst).last_or_none(lambda x: x != 'c')
 674        'b'
 675
 676        Exmaple 3:
 677        >>> lst = []
 678        >>> it(lst).last_or_none(lambda x: x != 'c') is None
 679        True
 680        """
 681        last: Optional[T] = None
 682        for i in self if predicate is None else self.filter(predicate):
 683            last = i
 684        return last
 685
 686    def index_of_or_none(self, element: T) -> Optional[int]:
 687        """
 688        Returns first index of [element], or None if the collection does not contain element.
 689
 690        Example 1:
 691        >>> lst = ['a', 'b', 'c']
 692        >>> it(lst).index_of_or_none('b')
 693        1
 694
 695        Example 2:
 696        >>> lst = ['a', 'b', 'c']
 697        >>> it(lst).index_of_or_none('d')
 698        """
 699        for i, x in enumerate(self):
 700            if x == element:
 701                return i
 702        return None
 703
 704    def index_of(self, element: T) -> int:
 705        """
 706        Returns first index of [element], or -1 if the collection does not contain element.
 707
 708        Example 1:
 709        >>> lst = ['a', 'b', 'c']
 710        >>> it(lst).index_of('b')
 711        1
 712
 713        Example 2:
 714        >>> lst = ['a', 'b', 'c']
 715        >>> it(lst).index_of('d')
 716        -1
 717        """
 718        return none_or(self.index_of_or_none(element), -1)
 719
 720    def index_of_or(self, element: T, default: int) -> int:
 721        """
 722        Returns first index of [element], or default value if the collection does not contain element.
 723
 724        Example 1:
 725        >>> lst = ['a', 'b', 'c']
 726        >>> it(lst).index_of_or('b', 1)
 727        1
 728
 729        Example 2:
 730        >>> lst = ['a', 'b', 'c']
 731        >>> it(lst).index_of_or('d', 0)
 732        0
 733        """
 734        return none_or(self.index_of_or_none(element), default)
 735
 736    def index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
 737        """
 738        Returns first index of [element], or computes the value from a callback if the collection does not contain element.
 739
 740        Example 1:
 741        >>> lst = ['a', 'b', 'c']
 742        >>> it(lst).index_of_or_else('b', lambda: 2)
 743        1
 744
 745        Example 2:
 746        >>> lst = ['a', 'b', 'c']
 747        >>> it(lst).index_of_or_else('d', lambda: 0)
 748        0
 749        """
 750        return none_or_else(self.index_of_or_none(element), f)
 751
 752    def last_index_of_or_none(self, element: T) -> Optional[int]:
 753        """
 754         Returns last index of [element], or None if the collection does not contain element.
 755
 756        Example 1:
 757        >>> lst = ['a', 'b', 'c', 'b']
 758        >>> it(lst).last_index_of_or_none('b')
 759        3
 760
 761        Example 2:
 762        >>> lst = ['a', 'b', 'c']
 763        >>> it(lst).last_index_of_or_none('d')
 764        """
 765        seq = self.reversed()
 766        last_idx = len(seq) - 1
 767        for i, x in enumerate(seq):
 768            if x == element:
 769                return last_idx - i
 770        return None
 771
 772    def last_index_of(self, element: T) -> int:
 773        """
 774         Returns last index of [element], or -1 if the collection does not contain element.
 775
 776        Example 1:
 777        >>> lst = ['a', 'b', 'c', 'b']
 778        >>> it(lst).last_index_of('b')
 779        3
 780
 781        Example 2:
 782        >>> lst = ['a', 'b', 'c']
 783        >>> it(lst).last_index_of('d')
 784        -1
 785        """
 786        return none_or(self.last_index_of_or_none(element), -1)
 787
 788    def last_index_of_or(self, element: T, default: int) -> int:
 789        """
 790         Returns last index of [element], or default value if the collection does not contain element.
 791
 792        Example 1:
 793        >>> lst = ['a', 'b', 'c', 'b']
 794        >>> it(lst).last_index_of_or('b', 0)
 795        3
 796
 797        Example 2:
 798        >>> lst = ['a', 'b', 'c']
 799        >>> it(lst).last_index_of_or('d', len(lst))
 800        3
 801        """
 802        return none_or(self.last_index_of_or_none(element), default)
 803
 804    def last_index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
 805        """
 806         Returns last index of [element], or computes the value from a callback if the collection does not contain element.
 807
 808        Example 1:
 809        >>> lst = ['a', 'b', 'c', 'b']
 810        >>> it(lst).last_index_of_or_else('b', lambda: 0)
 811        3
 812
 813        Example 2:
 814        >>> lst = ['a', 'b', 'c']
 815        >>> it(lst).last_index_of_or_else('d', lambda: len(lst))
 816        3
 817        """
 818        return none_or_else(self.last_index_of_or_none(element), f)
 819
 820    @overload
 821    def index_of_first_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ...
 822    @overload
 823    def index_of_first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ...
 824    @overload
 825    def index_of_first_or_none(
 826        self, predicate: Callable[[T, int, Stream[T]], bool]
 827    ) -> Optional[int]: ...
 828    def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
 829        """
 830        Returns first index of element matching the given [predicate], or None if no such element was found.
 831
 832        Example 1:
 833        >>> lst = ['a', 'b', 'c']
 834        >>> it(lst).index_of_first_or_none(lambda x: x == 'b')
 835        1
 836
 837        Example 2:
 838        >>> lst = ['a', 'b', 'c']
 839        >>> it(lst).index_of_first_or_none(lambda x: x == 'd')
 840        """
 841        predicate = self.__callback_overload_warpper__(predicate)
 842        for i, x in enumerate(self):
 843            if predicate(x):
 844                return i
 845        return None
 846
 847    @overload
 848    def index_of_first(self, predicate: Callable[[T], bool]) -> int: ...
 849    @overload
 850    def index_of_first(self, predicate: Callable[[T, int], bool]) -> int: ...
 851    @overload
 852    def index_of_first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
 853    def index_of_first(self, predicate: Callable[..., bool]) -> int:
 854        """
 855        Returns first index of element matching the given [predicate], or -1 if no such element was found.
 856
 857        Example 1:
 858        >>> lst = ['a', 'b', 'c']
 859        >>> it(lst).index_of_first(lambda x: x == 'b')
 860        1
 861
 862        Example 2:
 863        >>> lst = ['a', 'b', 'c']
 864        >>> it(lst).index_of_first(lambda x: x == 'd')
 865        -1
 866
 867        Example 3:
 868        >>> lst = ['a', 'b', 'c']
 869        >>> it(lst).index_of_first(lambda x: x == 'a')
 870        0
 871        """
 872        return none_or(self.index_of_first_or_none(predicate), -1)
 873
 874    @overload
 875    def index_of_first_or(self, predicate: Callable[[T], bool], default: int) -> int: ...
 876    @overload
 877    def index_of_first_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ...
 878    @overload
 879    def index_of_first_or(
 880        self, predicate: Callable[[T, int, Stream[T]], bool], default: int
 881    ) -> int: ...
 882    def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int:
 883        """
 884        Returns first index of element matching the given [predicate], or default value if no such element was found.
 885
 886        Example 1:
 887        >>> lst = ['a', 'b', 'c']
 888        >>> it(lst).index_of_first_or(lambda x: x == 'b', 0)
 889        1
 890
 891        Example 2:
 892        >>> lst = ['a', 'b', 'c']
 893        >>> it(lst).index_of_first_or(lambda x: x == 'd', 0)
 894        0
 895
 896        Example 3:
 897        >>> lst = ['a', 'b', 'c']
 898        >>> it(lst).index_of_first_or(lambda x: x == 'a', 0)
 899        0
 900        """
 901        return none_or(self.index_of_first_or_none(predicate), default)
 902
 903    @overload
 904    def index_of_first_or_else(
 905        self, predicate: Callable[[T], bool], f: Callable[[], int]
 906    ) -> int: ...
 907    @overload
 908    def index_of_first_or_else(
 909        self, predicate: Callable[[T, int], bool], f: Callable[[], int]
 910    ) -> int: ...
 911    @overload
 912    def index_of_first_or_else(
 913        self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int]
 914    ) -> int: ...
 915    def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
 916        """
 917        Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found.
 918
 919        Example 1:
 920        >>> lst = ['a', 'b', 'c']
 921        >>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst))
 922        1
 923
 924        Example 2:
 925        >>> lst = ['a', 'b', 'c']
 926        >>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst))
 927        3
 928
 929        Example 3:
 930        >>> lst = ['a', 'b', 'c']
 931        >>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst))
 932        0
 933        """
 934        return none_or_else(self.index_of_first_or_none(predicate), f)
 935
 936    @overload
 937    def index_of_last_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ...
 938    @overload
 939    def index_of_last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ...
 940    @overload
 941    def index_of_last_or_none(
 942        self, predicate: Callable[[T, int, Stream[T]], bool]
 943    ) -> Optional[int]: ...
 944    def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
 945        """
 946        Returns last index of element matching the given [predicate], or -1 if no such element was found.
 947
 948        Example 1:
 949        >>> lst = ['a', 'b', 'c', 'b']
 950        >>> it(lst).index_of_last_or_none(lambda x: x == 'b')
 951        3
 952
 953        Example 2:
 954        >>> lst = ['a', 'b', 'c']
 955        >>> it(lst).index_of_last_or_none(lambda x: x == 'd')
 956        """
 957        seq = self.reversed()
 958        last_idx = len(seq) - 1
 959        predicate = self.__callback_overload_warpper__(predicate)
 960        for i, x in enumerate(seq):
 961            if predicate(x):
 962                return last_idx - i
 963        return None
 964
 965    @overload
 966    def index_of_last(self, predicate: Callable[[T], bool]) -> int: ...
 967    @overload
 968    def index_of_last(self, predicate: Callable[[T, int], bool]) -> int: ...
 969    @overload
 970    def index_of_last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
 971    def index_of_last(self, predicate: Callable[..., bool]) -> int:
 972        """
 973        Returns last index of element matching the given [predicate], or -1 if no such element was found.
 974
 975        Example 1:
 976        >>> lst = ['a', 'b', 'c', 'b']
 977        >>> it(lst).index_of_last(lambda x: x == 'b')
 978        3
 979
 980        Example 2:
 981        >>> lst = ['a', 'b', 'c']
 982        >>> it(lst).index_of_last(lambda x: x == 'd')
 983        -1
 984
 985        Example 3:
 986        >>> lst = ['a', 'b', 'c']
 987        >>> it(lst).index_of_last(lambda x: x == 'a')
 988        0
 989        """
 990        return none_or(self.index_of_last_or_none(predicate), -1)
 991
 992    @overload
 993    def index_of_last_or(self, predicate: Callable[[T], bool], default: int) -> int: ...
 994    @overload
 995    def index_of_last_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ...
 996    @overload
 997    def index_of_last_or(
 998        self, predicate: Callable[[T, int, Stream[T]], bool], default: int
 999    ) -> int: ...
1000    def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int:
1001        """
1002        Returns last index of element matching the given [predicate], or default value if no such element was found.
1003
1004        Example 1:
1005        >>> lst = ['a', 'b', 'c', 'b']
1006        >>> it(lst).index_of_last_or(lambda x: x == 'b', 0)
1007        3
1008
1009        Example 2:
1010        >>> lst = ['a', 'b', 'c']
1011        >>> it(lst).index_of_last_or(lambda x: x == 'd', -99)
1012        -99
1013
1014        Example 3:
1015        >>> lst = ['a', 'b', 'c']
1016        >>> it(lst).index_of_last_or(lambda x: x == 'a', 0)
1017        0
1018        """
1019        return none_or(self.index_of_last_or_none(predicate), default)
1020
1021    @overload
1022    def index_of_last_or_else(
1023        self, predicate: Callable[[T], bool], f: Callable[[], int]
1024    ) -> int: ...
1025    @overload
1026    def index_of_last_or_else(
1027        self, predicate: Callable[[T, int], bool], f: Callable[[], int]
1028    ) -> int: ...
1029    @overload
1030    def index_of_last_or_else(
1031        self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int]
1032    ) -> int: ...
1033    def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
1034        """
1035        Returns last index of element matching the given [predicate], or default value if no such element was found.
1036
1037        Example 1:
1038        >>> lst = ['a', 'b', 'c', 'b']
1039        >>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst))
1040        3
1041
1042        Example 2:
1043        >>> lst = ['a', 'b', 'c']
1044        >>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst))
1045        -3
1046
1047        Example 3:
1048        >>> lst = ['a', 'b', 'c']
1049        >>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst))
1050        0
1051        """
1052        return none_or_else(self.index_of_last_or_none(predicate), f)
1053
1054    @overload
1055    def single(self) -> T: ...
1056    @overload
1057    def single(self, predicate: Callable[[T], bool]) -> T: ...
1058    @overload
1059    def single(self, predicate: Callable[[T, int], bool]) -> T: ...
1060    @overload
1061    def single(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ...
1062    def single(self, predicate: Optional[Callable[..., bool]] = None) -> T:
1063        """
1064        Returns the single element matching the given [predicate], or throws exception if there is no
1065        or more than one matching element.
1066
1067        Exmaple 1:
1068        >>> lst = ['a']
1069        >>> it(lst).single()
1070        'a'
1071
1072        Exmaple 2:
1073        >>> lst = []
1074        >>> it(lst).single() is None
1075        Traceback (most recent call last):
1076        ...
1077        ValueError: Stream contains no element matching the predicate.
1078
1079        Exmaple 2:
1080        >>> lst = ['a', 'b']
1081        >>> it(lst).single() is None
1082        Traceback (most recent call last):
1083        ...
1084        ValueError: Stream contains more than one matching element.
1085        """
1086        single: Optional[T] = None
1087        found = False
1088        for i in self if predicate is None else self.filter(predicate):
1089            if found:
1090                raise ValueError("Stream contains more than one matching element.")
1091            single = i
1092            found = True
1093        if single is None:
1094            raise ValueError("Stream contains no element matching the predicate.")
1095        return single
1096
1097    @overload
1098    def single_or_none(self) -> Optional[T]: ...
1099    @overload
1100    def single_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ...
1101    @overload
1102    def single_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ...
1103    @overload
1104    def single_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ...
1105    def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
1106        """
1107        Returns the single element matching the given [predicate], or `None` if element was not found
1108        or more than one element was found.
1109
1110        Exmaple 1:
1111        >>> lst = ['a']
1112        >>> it(lst).single_or_none()
1113        'a'
1114
1115        Exmaple 2:
1116        >>> lst = []
1117        >>> it(lst).single_or_none()
1118
1119        Exmaple 2:
1120        >>> lst = ['a', 'b']
1121        >>> it(lst).single_or_none()
1122
1123        """
1124        single: Optional[T] = None
1125        found = False
1126        for i in self if predicate is None else self.filter(predicate):
1127            if found:
1128                return None
1129            single = i
1130            found = True
1131        if not found:
1132            return None
1133        return single
1134
1135    # noinspection PyShadowingNames
1136    def drop(self, n: int) -> Stream[T]:
1137        """
1138        Returns a Stream containing all elements except first [n] elements.
1139
1140        Example 1:
1141        >>> lst = ['a', 'b', 'c']
1142        >>> it(lst).drop(0).to_list()
1143        ['a', 'b', 'c']
1144
1145        Example 2:
1146        >>> lst = ['a', 'b', 'c']
1147        >>> it(lst).drop(1).to_list()
1148        ['b', 'c']
1149
1150        Example 2:
1151        >>> lst = ['a', 'b', 'c']
1152        >>> it(lst).drop(4).to_list()
1153        []
1154        """
1155        if n < 0:
1156            raise ValueError(f"Requested element count {n} is less than zero.")
1157        if n == 0:
1158            return self
1159
1160        from .drop import DropTransform
1161
1162        return it(DropTransform(self, n))
1163
1164    # noinspection PyShadowingNames
1165    @overload
1166    def drop_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1167    @overload
1168    def drop_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1169    @overload
1170    def drop_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1171    def drop_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1172        """
1173        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1174
1175        Example 1:
1176        >>> lst = [1, 2, 3, 4, 1]
1177        >>> it(lst).drop_while(lambda x: x < 3 ).to_list()
1178        [3, 4, 1]
1179        """
1180        from .drop_while import DropWhileTransform
1181
1182        return it(DropWhileTransform(self, self.__callback_overload_warpper__(predicate)))
1183
1184    # noinspection PyShadowingNames
1185    @overload
1186    def drop_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1187    @overload
1188    def drop_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1189    @overload
1190    def drop_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1191    def drop_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1192        """
1193        Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate].
1194
1195        Example 1:
1196        >>> lst = [1, 2, 3, 4, 1]
1197        >>> it(lst).drop_until(lambda x: x >= 3).to_list()
1198        [3, 4, 1]
1199
1200        Example 2:
1201        >>> lst = [1, 2, 1, 4]
1202        >>> it(lst).drop_until(lambda x: x == 4).to_list()
1203        [4]
1204        """
1205        from .drop_until import DropUntilTransform
1206
1207        return it(DropUntilTransform(self, self.__callback_overload_warpper__(predicate)))
1208
1209    def drop_last(self, n: int) -> Stream[T]:
1210        """
1211        Returns a Stream containing all elements except last [n] elements.
1212
1213        Example 1:
1214        >>> lst = ['a', 'b', 'c']
1215        >>> it(lst).drop_last(0).to_list()
1216        ['a', 'b', 'c']
1217
1218        Example 2:
1219        >>> lst = ['a', 'b', 'c']
1220        >>> it(lst).drop_last(1).to_list()
1221        ['a', 'b']
1222
1223        Example 3:
1224        >>> lst = ['a', 'b', 'c']
1225        >>> it(lst).drop_last(4).to_list()
1226        []
1227        """
1228        if n < 0:
1229            raise ValueError(f"Requested element count {n} is less than zero.")
1230        if n == 0:
1231            return self
1232
1233        size = len(self)
1234        if size <= n:
1235            return Stream([])
1236        return self.take(size - n)
1237
1238    def skip(self, n: int) -> Stream[T]:
1239        """
1240        Returns a Stream containing all elements except first [n] elements.
1241
1242        Example 1:
1243        >>> lst = ['a', 'b', 'c']
1244        >>> it(lst).skip(0).to_list()
1245        ['a', 'b', 'c']
1246
1247         Example 2:
1248        >>> lst = ['a', 'b', 'c']
1249        >>> it(lst).skip(1).to_list()
1250        ['b', 'c']
1251
1252        Example 2:
1253        >>> lst = ['a', 'b', 'c']
1254        >>> it(lst).skip(4).to_list()
1255        []
1256        """
1257        return self.drop(n)
1258
1259    @overload
1260    def skip_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1261    @overload
1262    def skip_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1263    @overload
1264    def skip_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1265    def skip_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1266        """
1267        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1268
1269        Example 1:
1270        >>> lst = [1, 2, 3, 4, 1]
1271        >>> it(lst).skip_while(lambda x: x < 3 ).to_list()
1272        [3, 4, 1]
1273        """
1274        return self.drop_while(predicate)
1275
1276    def take(self, n: int) -> Stream[T]:
1277        """
1278        Returns an Stream containing first [n] elements.
1279
1280        Example 1:
1281        >>> a = ['a', 'b', 'c']
1282        >>> it(a).take(0).to_list()
1283        []
1284
1285        Example 2:
1286        >>> a = ['a', 'b', 'c']
1287        >>> it(a).take(2).to_list()
1288        ['a', 'b']
1289        """
1290        if n < 0:
1291            raise ValueError(f"Requested element count {n} is less than zero.")
1292        if n == 0:
1293            return Stream([])
1294        from .take import TakeTransform
1295
1296        return it(TakeTransform(self, n))
1297
1298    # noinspection PyShadowingNames
1299    @overload
1300    def take_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1301    @overload
1302    def take_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1303    @overload
1304    def take_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1305    def take_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1306        """
1307        Returns an Stream containing first elements satisfying the given [predicate].
1308
1309        Example 1:
1310        >>> lst = ['a', 'b', 'c', 'd']
1311        >>> it(lst).take_while(lambda x: x in ['a', 'b']).to_list()
1312        ['a', 'b']
1313        """
1314        from .take_while import TakeWhileTransform
1315
1316        return it(TakeWhileTransform(self, self.__callback_overload_warpper__(predicate)))
1317
1318    # noinspection PyShadowingNames
1319    @overload
1320    def take_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ...
1321    @overload
1322    def take_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ...
1323    @overload
1324    def take_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ...
1325    def take_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1326        """
1327        Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate].
1328
1329        Example 1:
1330        >>> lst = [1, 2, 3, 4]
1331        >>> it(lst).take_until(lambda x: x > 2).to_list()
1332        [1, 2]
1333
1334        Example 2:
1335        >>> lst = [1, 2, 3, 4]
1336        >>> it(lst).take_until(lambda x: x > 10).to_list()
1337        [1, 2, 3, 4]
1338        """
1339        from .take_until import TakeUntilTransform
1340
1341        return it(TakeUntilTransform(self, self.__callback_overload_warpper__(predicate)))
1342
1343    def take_last(self, n: int) -> Stream[T]:
1344        """
1345        Returns an Stream containing last [n] elements.
1346
1347        Example 1:
1348        >>> a = ['a', 'b', 'c']
1349        >>> it(a).take_last(0).to_list()
1350        []
1351
1352        Example 2:
1353        >>> a = ['a', 'b', 'c']
1354        >>> it(a).take_last(2).to_list()
1355        ['b', 'c']
1356
1357        Example 3:
1358        >>> a = ['a', 'b', 'c']
1359        >>> it(a).take_last(10).to_list()
1360        ['a', 'b', 'c']
1361        """
1362        if n < 0:
1363            raise ValueError(f"Requested element count {n} is less than zero.")
1364        if n == 0:
1365            return Stream([])
1366
1367        return self.drop(max(len(self) - n, 0))
1368
1369    # noinspection PyShadowingNames
1370    def sorted(self) -> Stream[T]:
1371        """
1372        Returns an Stream that yields elements of this Stream sorted according to their natural sort order.
1373
1374        Example 1:
1375        >>> lst = ['b', 'a', 'e', 'c']
1376        >>> it(lst).sorted().to_list()
1377        ['a', 'b', 'c', 'e']
1378
1379         Example 2:
1380        >>> lst = [2, 1, 4, 3]
1381        >>> it(lst).sorted().to_list()
1382        [1, 2, 3, 4]
1383        """
1384        lst = list(self)
1385        lst.sort()  # type: ignore
1386        return it(lst)
1387
1388    # noinspection PyShadowingNames
1389    @overload
1390    def sorted_by(self, key_selector: Callable[[T], SupportsRichComparisonT]) -> Stream[T]: ...
1391    @overload
1392    def sorted_by(self, key_selector: Callable[[T, int], SupportsRichComparisonT]) -> Stream[T]: ...
1393    @overload
1394    def sorted_by(
1395        self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT]
1396    ) -> Stream[T]: ...
1397    def sorted_by(self, key_selector: Callable[..., SupportsRichComparisonT]) -> Stream[T]:
1398        """
1399        Returns a sequence that yields elements of this sequence sorted according to natural sort
1400        order of the value returned by specified [key_selector] function.
1401
1402        Example 1:
1403        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1404        >>> it(lst).sorted_by(lambda x: x['name']).to_list()
1405        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1406        >>> it(lst).sorted_by(lambda x: x['age']).to_list()
1407        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1408        """
1409        lst = list(self)
1410        lst.sort(key=self.__callback_overload_warpper__(key_selector))
1411        return it(lst)
1412
1413    def sorted_descending(self) -> Stream[T]:
1414        """
1415        Returns a Stream of all elements sorted descending according to their natural sort order.
1416
1417        Example 1:
1418        >>> lst = ['b', 'c', 'a']
1419        >>> it(lst).sorted_descending().to_list()
1420        ['c', 'b', 'a']
1421        """
1422        return self.sorted().reversed()
1423
1424    @overload
1425    def sorted_by_descending(
1426        self, key_selector: Callable[[T], SupportsRichComparisonT]
1427    ) -> Stream[T]: ...
1428    @overload
1429    def sorted_by_descending(
1430        self, key_selector: Callable[[T, int], SupportsRichComparisonT]
1431    ) -> Stream[T]: ...
1432    @overload
1433    def sorted_by_descending(
1434        self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT]
1435    ) -> Stream[T]: ...
1436    def sorted_by_descending(
1437        self, key_selector: Callable[..., SupportsRichComparisonT]
1438    ) -> Stream[T]:
1439        """
1440        Returns a sequence that yields elements of this sequence sorted descending according
1441        to natural sort order of the value returned by specified [key_selector] function.
1442
1443        Example 1:
1444        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1445        >>> it(lst).sorted_by_descending(lambda x: x['name']).to_list()
1446        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1447        >>> it(lst).sorted_by_descending(lambda x: x['age']).to_list()
1448        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1449        """
1450        return self.sorted_by(key_selector).reversed()
1451
1452    # noinspection PyShadowingNames
1453    def sorted_with(self, comparator: Callable[[T, T], int]) -> Stream[T]:
1454        """
1455        Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
1456
1457        Example 1:
1458        >>> lst = ['aa', 'bbb', 'c']
1459        >>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list()
1460        ['c', 'aa', 'bbb']
1461        """
1462        from functools import cmp_to_key
1463
1464        lst = list(self)
1465        lst.sort(key=cmp_to_key(comparator))
1466        return it(lst)
1467
1468    @overload
1469    def associate(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ...
1470    @overload
1471    def associate(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ...
1472    @overload
1473    def associate(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ...
1474    def associate(self, transform: Callable[..., Tuple[K, V]]) -> Dict[K, V]:
1475        """
1476        Returns a [Dict] containing key-value Tuple provided by [transform] function
1477        applied to elements of the given Stream.
1478
1479        Example 1:
1480        >>> lst = ['1', '2', '3']
1481        >>> it(lst).associate(lambda x: (int(x), x))
1482        {1: '1', 2: '2', 3: '3'}
1483        """
1484        transform = self.__callback_overload_warpper__(transform)
1485        dic: Dict[K, V] = dict()
1486        for i in self:
1487            k, v = transform(i)
1488            dic[k] = v
1489        return dic
1490
1491    @overload
1492    def associate_by(self, key_selector: Callable[[T], K]) -> Dict[K, T]: ...
1493    @overload
1494    def associate_by(self, key_selector: Callable[[T, int], K]) -> Dict[K, T]: ...
1495    @overload
1496    def associate_by(self, key_selector: Callable[[T, int, Stream[T]], K]) -> Dict[K, T]: ...
1497    @overload
1498    def associate_by(
1499        self, key_selector: Callable[[T], K], value_transform: Callable[[T], V]
1500    ) -> Dict[K, V]: ...
1501    def associate_by(
1502        self,
1503        key_selector: Callable[..., K],
1504        value_transform: Optional[Callable[[T], V]] = None,
1505    ) -> Union[Dict[K, T], Dict[K, V]]:
1506        """
1507        Returns a [Dict] containing key-value Tuple provided by [transform] function
1508        applied to elements of the given Stream.
1509
1510        Example 1:
1511        >>> lst = ['1', '2', '3']
1512        >>> it(lst).associate_by(lambda x: int(x))
1513        {1: '1', 2: '2', 3: '3'}
1514
1515        Example 2:
1516        >>> lst = ['1', '2', '3']
1517        >>> it(lst).associate_by(lambda x: int(x), lambda x: x+x)
1518        {1: '11', 2: '22', 3: '33'}
1519
1520        """
1521        key_selector = self.__callback_overload_warpper__(key_selector)
1522
1523        dic: Dict[K, Any] = dict()
1524        for i in self:
1525            k = key_selector(i)
1526            dic[k] = i if value_transform is None else value_transform(i)
1527        return dic
1528
1529    @overload
1530    def associate_by_to(
1531        self, destination: Dict[K, T], key_selector: Callable[[T], K]
1532    ) -> Dict[K, T]: ...
1533    @overload
1534    def associate_by_to(
1535        self,
1536        destination: Dict[K, V],
1537        key_selector: Callable[[T], K],
1538        value_transform: Callable[[T], V],
1539    ) -> Dict[K, V]: ...
1540    def associate_by_to(
1541        self,
1542        destination: Dict[K, Any],
1543        key_selector: Callable[[T], K],
1544        value_transform: Optional[Callable[[T], Any]] = None,
1545    ) -> Dict[K, Any]:
1546        """
1547        Returns a [Dict] containing key-value Tuple provided by [transform] function
1548        applied to elements of the given Stream.
1549
1550        Example 1:
1551        >>> lst = ['1', '2', '3']
1552        >>> it(lst).associate_by_to({}, lambda x: int(x))
1553        {1: '1', 2: '2', 3: '3'}
1554
1555        Example 2:
1556        >>> lst = ['1', '2', '3']
1557        >>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' )
1558        {1: '1!', 2: '2!', 3: '3!'}
1559
1560        """
1561        for i in self:
1562            k = key_selector(i)
1563            destination[k] = i if value_transform is None else value_transform(i)
1564        return destination
1565
1566    @overload
1567    def all(self, predicate: Callable[[T], bool]) -> bool: ...
1568    @overload
1569    def all(self, predicate: Callable[[T, int], bool]) -> bool: ...
1570    @overload
1571    def all(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ...
1572    def all(self, predicate: Callable[..., bool]) -> bool:
1573        """
1574        Returns True if all elements of the Stream satisfy the specified [predicate] function.
1575
1576        Example 1:
1577        >>> lst = [1, 2, 3]
1578        >>> it(lst).all(lambda x: x > 0)
1579        True
1580        >>> it(lst).all(lambda x: x > 1)
1581        False
1582        """
1583        predicate = self.__callback_overload_warpper__(predicate)
1584        for i in self:
1585            if not predicate(i):
1586                return False
1587        return True
1588
1589    @overload
1590    def any(self, predicate: Callable[[T], bool]) -> bool: ...
1591    @overload
1592    def any(self, predicate: Callable[[T, int], bool]) -> bool: ...
1593    @overload
1594    def any(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ...
1595    def any(self, predicate: Callable[..., bool]) -> bool:
1596        """
1597        Returns True if any elements of the Stream satisfy the specified [predicate] function.
1598
1599        Example 1:
1600        >>> lst = [1, 2, 3]
1601        >>> it(lst).any(lambda x: x > 0)
1602        True
1603        >>> it(lst).any(lambda x: x > 3)
1604        False
1605        """
1606        predicate = self.__callback_overload_warpper__(predicate)
1607        for i in self:
1608            if predicate(i):
1609                return True
1610        return False
1611
1612    @overload
1613    def count(self) -> int: ...
1614    @overload
1615    def count(self, predicate: Callable[[T], bool]) -> int: ...
1616    @overload
1617    def count(self, predicate: Callable[[T, int], bool]) -> int: ...
1618    @overload
1619    def count(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ...
1620    def count(self, predicate: Optional[Callable[..., bool]] = None) -> int:
1621        """
1622        Returns the number of elements in the Stream that satisfy the specified [predicate] function.
1623
1624        Example 1:
1625        >>> lst = [1, 2, 3]
1626        >>> it(lst).count()
1627        3
1628        >>> it(lst).count(lambda x: x > 0)
1629        3
1630        >>> it(lst).count(lambda x: x > 2)
1631        1
1632        """
1633        if predicate is None:
1634            return len(self)
1635        predicate = self.__callback_overload_warpper__(predicate)
1636        return sum(1 for i in self if predicate(i))
1637
1638    def contains(self, value: T) -> bool:
1639        """
1640        Returns True if the Stream contains the specified [value].
1641
1642        Example 1:
1643        >>> lst = [1, 2, 3]
1644        >>> it(lst).contains(1)
1645        True
1646        >>> it(lst).contains(4)
1647        False
1648        """
1649        return value in self
1650
1651    def element_at(self, index: int) -> T:
1652        """
1653        Returns the element at the specified [index] in the Stream.
1654
1655        Example 1:
1656        >>> lst = [1, 2, 3]
1657        >>> it(lst).element_at(1)
1658        2
1659
1660        Example 2:
1661        >>> lst = [1, 2, 3]
1662        >>> it(lst).element_at(3)
1663        Traceback (most recent call last):
1664        ...
1665        IndexError: Index 3 out of range
1666        """
1667        return self.element_at_or_else(
1668            index, lambda index: throw(IndexError(f"Index {index} out of range"))
1669        )
1670
1671    @overload
1672    def element_at_or_else(self, index: int) -> Optional[T]:
1673        """
1674        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1675
1676        Example 1:
1677        >>> lst = [1, 2, 3]
1678        >>> it(lst).element_at_or_else(1, 'default')
1679        2
1680        >>> it(lst).element_at_or_else(4, lambda x: 'default')
1681        'default'
1682        """
1683        ...
1684
1685    @overload
1686    def element_at_or_else(self, index: int, default: T) -> T: ...
1687    @overload
1688    def element_at_or_else(self, index: int, default: Callable[[int], T]) -> T: ...
1689    def element_at_or_else(
1690        self, index: int, default: Union[Callable[[int], T], T, None] = None
1691    ) -> Optional[T]:
1692        """
1693        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1694
1695        Example 1:
1696        >>> lst = [1, 2, 3]
1697        >>> it(lst).element_at_or_else(1, lambda x: 'default')
1698        2
1699        >>> it(lst).element_at_or_else(4, lambda x: 'default')
1700        'default'
1701
1702        """
1703        if index >= 0:
1704            if (
1705                isinstance(self.__transform__, NonTransform)
1706                and isinstance(self.__transform__.iter, list)
1707                and index < len(self.__transform__.iter)
1708            ):
1709                return self.__transform__.iter[index]
1710            for i, e in enumerate(self):
1711                if i == index:
1712                    return e
1713        return default(index) if callable(default) else default  # type: ignore
1714
1715    def element_at_or_default(self, index: int, default: T) -> T:
1716        """
1717        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1718
1719        Example 1:
1720        >>> lst = [1, 2, 3]
1721        >>> it(lst).element_at_or_default(1, 'default')
1722        2
1723        >>> it(lst).element_at_or_default(4, 'default')
1724        'default'
1725
1726        """
1727        return self.element_at_or_else(index, default)
1728
1729    def element_at_or_none(self, index: int) -> Optional[T]:
1730        """
1731        Returns the element at the specified [index] in the Stream or None if the index is out of bounds.
1732
1733        Example 1:
1734        >>> lst = [1, 2, 3]
1735        >>> it(lst).element_at_or_none(1)
1736        2
1737        >>> it(lst).element_at_or_none(4) is None
1738        True
1739        """
1740        return self.element_at_or_else(index)
1741
1742    def distinct(self) -> Stream[T]:
1743        """
1744        Returns a new Stream containing the distinct elements of the given Stream.
1745
1746        Example 1:
1747        >>> lst = [1, 2, 3, 1, 2, 3]
1748        >>> it(lst).distinct().to_list()
1749        [1, 2, 3]
1750
1751        Example 2:
1752        >>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1753        >>> it(lst).distinct().sorted().to_list()
1754        [(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1755
1756        """
1757        from .distinct import DistinctTransform
1758
1759        return it(DistinctTransform(self))
1760
1761    @overload
1762    def distinct_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ...
1763    @overload
1764    def distinct_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ...
1765    @overload
1766    def distinct_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ...
1767    def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
1768        """
1769        Returns a new Stream containing the distinct elements of the given Stream.
1770
1771        Example 1:
1772        >>> lst = [1, 2, 3, 1, 2, 3]
1773        >>> it(lst).distinct_by(lambda x: x%2).to_list()
1774        [1, 2]
1775        """
1776        from .distinct import DistinctTransform
1777
1778        return it(DistinctTransform(self, self.__callback_overload_warpper__(key_selector)))
1779
1780    @overload
1781    def reduce(self, accumulator: Callable[[T, T], T]) -> T: ...
1782    @overload
1783    def reduce(self, accumulator: Callable[[U, T], U], initial: U) -> U: ...
1784    def reduce(self, accumulator: Callable[..., U], initial: Optional[U] = None) -> Optional[U]:
1785        """
1786        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1787
1788        Example 1:
1789        >>> lst = [1, 2, 3]
1790        >>> it(lst).reduce(lambda x, y: x+y)
1791        6
1792        """
1793        result: Optional[U] = initial
1794        for i, e in enumerate(self):
1795            if i == 0 and initial is None:
1796                result = e  # type: ignore
1797                continue
1798
1799            result = accumulator(result, e)
1800        return result
1801
1802    def fold(self, initial: U, accumulator: Callable[[U, T], U]) -> U:
1803        """
1804        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1805
1806        Example 1:
1807        >>> lst = [1, 2, 3]
1808        >>> it(lst).fold(0, lambda x, y: x+y)
1809        6
1810        """
1811        return self.reduce(accumulator, initial)
1812
1813    @overload
1814    def sum_of(self, selector: Callable[[T], int]) -> int: ...
1815    @overload
1816    def sum_of(self, selector: Callable[[T], float]) -> float: ...
1817    def sum_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1818        """
1819        Returns the sum of the elements of the given Stream.
1820
1821        Example 1:
1822        >>> lst = [1, 2, 3]
1823        >>> it(lst).sum_of(lambda x: x)
1824        6
1825        """
1826        return sum(selector(i) for i in self)
1827
1828    @overload
1829    def max_of(self, selector: Callable[[T], int]) -> int: ...
1830    @overload
1831    def max_of(self, selector: Callable[[T], float]) -> float: ...
1832    def max_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1833        """
1834        Returns the maximum element of the given Stream.
1835
1836        Example 1:
1837        >>> lst = [1, 2, 3]
1838        >>> it(lst).max_of(lambda x: x)
1839        3
1840        """
1841        return max(selector(i) for i in self)
1842
1843    @overload
1844    def max_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ...
1845    @overload
1846    def max_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ...
1847    def max_by_or_none(self, selector: Callable[[T], Union[float, int]]) -> Optional[T]:
1848        """
1849        Returns the first element yielding the largest value of the given function
1850        or `none` if there are no elements.
1851
1852        Example 1:
1853        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1854        >>> it(lst).max_by_or_none(lambda x: x["num"])
1855        {'name': 'B', 'num': 200}
1856
1857        Example 2:
1858        >>> lst = []
1859        >>> it(lst).max_by_or_none(lambda x: x["num"])
1860        """
1861
1862        max_item = None
1863        max_val = None
1864
1865        for item in self:
1866            val = selector(item)
1867            if max_val is None or val > max_val:
1868                max_item = item
1869                max_val = val
1870
1871        return max_item
1872
1873    @overload
1874    def max_by(self, selector: Callable[[T], int]) -> T: ...
1875    @overload
1876    def max_by(self, selector: Callable[[T], float]) -> T: ...
1877    def max_by(self, selector: Callable[[T], Union[float, int]]) -> T:
1878        """
1879        Returns the first element yielding the largest value of the given function.
1880
1881        Example 1:
1882        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1883        >>> it(lst).max_by(lambda x: x["num"])
1884        {'name': 'B', 'num': 200}
1885
1886        Exmaple 2:
1887        >>> lst = []
1888        >>> it(lst).max_by(lambda x: x["num"])
1889        Traceback (most recent call last):
1890        ...
1891        ValueError: Stream is empty.
1892        """
1893        max_item = self.max_by_or_none(selector)
1894        if max_item is None:
1895            raise ValueError("Stream is empty.")
1896        return max_item
1897
1898    @overload
1899    def min_of(self, selector: Callable[[T], int]) -> int:
1900        """
1901        Returns the minimum element of the given Stream.
1902
1903        Example 1:
1904        >>> lst = [1, 2, 3]
1905        >>> it(lst).min_of(lambda x: x)
1906        1
1907        """
1908        ...
1909
1910    @overload
1911    def min_of(self, selector: Callable[[T], float]) -> float: ...
1912    def min_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1913        return min(selector(i) for i in self)
1914
1915    @overload
1916    def min_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ...
1917    @overload
1918    def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ...
1919    def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]:
1920        """
1921        Returns the first element yielding the smallest value of the given function
1922        or `none` if there are no elements.
1923
1924        Example 1:
1925        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1926        >>> it(lst).min_by_or_none(lambda x: x["num"])
1927        {'name': 'A', 'num': 100}
1928
1929        Exmaple 2:
1930        >>> lst = []
1931        >>> it(lst).min_by_or_none(lambda x: x["num"])
1932        """
1933        min_item = None
1934        min_val = None
1935
1936        for item in self:
1937            val = selector(item)
1938            if min_val is None or val < min_val:
1939                min_item = item
1940                min_val = val
1941
1942        return min_item
1943
1944    @overload
1945    def min_by(self, selector: Callable[[T], int]) -> T: ...
1946    @overload
1947    def min_by(self, selector: Callable[[T], float]) -> T: ...
1948    def min_by(self, selector: Callable[[T], float]) -> T:
1949        """
1950        Returns the first element yielding the smallest value of the given function.
1951
1952        Example 1:
1953        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1954        >>> it(lst).min_by(lambda x: x["num"])
1955        {'name': 'A', 'num': 100}
1956
1957        Exmaple 2:
1958        >>> lst = []
1959        >>> it(lst).min_by(lambda x: x["num"])
1960        Traceback (most recent call last):
1961        ...
1962        ValueError: Stream is empty.
1963        """
1964        min_item = self.min_by_or_none(selector)
1965        if min_item is None:
1966            raise ValueError("Stream is empty.")
1967
1968        return min_item
1969
1970    def mean_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1971        """
1972        Returns the mean of the elements of the given Stream.
1973
1974        Example 1:
1975        >>> lst = [1, 2, 3]
1976        >>> it(lst).mean_of(lambda x: x)
1977        2.0
1978        """
1979        return self.sum_of(selector) / len(self)
1980
1981    @overload
1982    def sum(self: Stream[int]) -> int:
1983        """
1984        Returns the sum of the elements of the given Stream.
1985
1986        Example 1:
1987        >>> lst = [1, 2, 3]
1988        >>> it(lst).sum()
1989        6
1990        """
1991        ...
1992
1993    @overload
1994    def sum(self: Stream[float]) -> float: ...
1995    def sum(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
1996        """
1997        Returns the sum of the elements of the given Stream.
1998
1999        Example 1:
2000        >>> lst = [1, 2, 3]
2001        >>> it(lst).sum()
2002        6
2003        """
2004        return sum(self)
2005
2006    @overload
2007    def max(self: Stream[int]) -> int: ...
2008    @overload
2009    def max(self: Stream[float]) -> float: ...
2010    def max(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2011        """
2012        Returns the maximum element of the given Stream.
2013
2014        Example 1:
2015        >>> lst = [1, 2, 3]
2016        >>> it(lst).max()
2017        3
2018        """
2019        return max(self)
2020
2021    @overload
2022    def max_or_default(self: Stream[int]) -> int: ...
2023    @overload
2024    def max_or_default(self: Stream[int], default: V) -> Union[int, V]: ...
2025    @overload
2026    def max_or_default(self: Stream[float]) -> float: ...
2027    @overload
2028    def max_or_default(self: Stream[float], default: V) -> Union[float, V]: ...
2029    def max_or_default(
2030        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2031    ) -> Union[float, int, V, None]:
2032        """
2033        Returns the maximum element of the given Stream.
2034
2035        Example 1:
2036        >>> lst = [1, 2, 3]
2037        >>> it(lst).max_or_default()
2038        3
2039
2040        Example 2:
2041        >>> lst = []
2042        >>> it(lst).max_or_default() is None
2043        True
2044
2045        Example 3:
2046        >>> lst = []
2047        >>> it(lst).max_or_default(9)
2048        9
2049        """
2050        if self.is_empty():
2051            return default
2052        return max(self)
2053
2054    @overload
2055    def max_or_none(self: Stream[int]) -> int: ...
2056    @overload
2057    def max_or_none(self: Stream[float]) -> float: ...
2058    def max_or_none(
2059        self: Union[Stream[int], Stream[float]],
2060    ) -> Union[float, int, None]:
2061        """
2062        Returns the maximum element of the given Stream.
2063
2064        Example 1:
2065        >>> lst = [1, 2, 3]
2066        >>> it(lst).max_or_none()
2067        3
2068
2069        Example 2:
2070        >>> lst = []
2071        >>> it(lst).max_or_none() is None
2072        True
2073        """
2074        return self.max_or_default(None)
2075
2076    @overload
2077    def min(self: Stream[int]) -> int:
2078        """
2079        Returns the minimum element of the given Stream.
2080
2081        Example 1:
2082        >>> lst = [1, 2, 3]
2083        >>> it(lst).min()
2084        1
2085        """
2086        ...
2087
2088    @overload
2089    def min(self: Stream[float]) -> float: ...
2090    def min(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2091        """
2092        Returns the minimum element of the given Stream.
2093
2094        Example 1:
2095        >>> lst = [1, 2, 3]
2096        >>> it(lst).min()
2097        1
2098        """
2099        return min(self)
2100
2101    @overload
2102    def min_or_none(self: Stream[int]) -> Optional[int]:
2103        """
2104        Returns the minimum element of the given Stream.
2105
2106        Example 1:
2107        >>> lst = [1, 2, 3]
2108        >>> it(lst).min_or_none()
2109        1
2110        """
2111        ...
2112
2113    @overload
2114    def min_or_none(self: Stream[float]) -> Optional[float]: ...
2115    def min_or_none(
2116        self: Union[Stream[int], Stream[float]],
2117    ) -> Union[float, int, None]:
2118        """
2119        Returns the minimum element of the given Stream.
2120
2121        Example 1:
2122        >>> lst = [1, 2, 3]
2123        >>> it(lst).min_or_none()
2124        1
2125        """
2126        return self.min_or_default(None)
2127
2128    @overload
2129    def min_or_default(self: Stream[int]) -> int:
2130        """
2131        Returns the minimum element of the given Stream.
2132
2133        Example 1:
2134        >>> lst = [1, 2, 3]
2135        >>> it(lst).min_or_default()
2136        1
2137        """
2138        ...
2139
2140    @overload
2141    def min_or_default(self: Stream[int], default: V) -> Union[int, V]: ...
2142    @overload
2143    def min_or_default(self: Stream[float]) -> float: ...
2144    @overload
2145    def min_or_default(self: Stream[float], default: V) -> Union[float, V]: ...
2146    def min_or_default(
2147        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2148    ) -> Union[float, int, V, None]:
2149        """
2150        Returns the minimum element of the given Stream.
2151
2152        Example 1:
2153        >>> lst = [1, 2, 3]
2154        >>> it(lst).min_or_default()
2155        1
2156
2157        Example 2:
2158        >>> lst = []
2159        >>> it(lst).min_or_default(9)
2160        9
2161        """
2162        if self.is_empty():
2163            return default
2164        return min(self)
2165
2166    @overload
2167    def mean(self: Stream[int]) -> float:
2168        """
2169        Returns the mean of the elements of the given Stream.
2170
2171        Example 1:
2172        >>> lst = [1, 2, 3]
2173        >>> it(lst).mean()
2174        2.0
2175        """
2176        ...
2177
2178    @overload
2179    def mean(self: Stream[float]) -> float: ...
2180    def mean(self: Union[Stream[int], Stream[float]]) -> float:
2181        """
2182        Returns the mean of the elements of the given Stream.
2183
2184        Example 1:
2185        >>> lst = [1, 2, 3]
2186        >>> it(lst).mean()
2187        2.0
2188        """
2189        return self.sum() / len(self)
2190
2191    # noinspection PyShadowingNames
2192    def reversed(self) -> Stream[T]:
2193        """
2194        Returns a list with elements in reversed order.
2195
2196        Example 1:
2197        >>> lst = ['b', 'c', 'a']
2198        >>> it(lst).reversed().to_list()
2199        ['a', 'c', 'b']
2200        """
2201        lst = list(self)
2202        lst.reverse()
2203        return it(lst)
2204
2205    @overload
2206    def flat_map(self, transform: Callable[[T], Iterable[U]]) -> Stream[U]: ...
2207    @overload
2208    def flat_map(self, transform: Callable[[T, int], Iterable[U]]) -> Stream[U]: ...
2209    @overload
2210    def flat_map(self, transform: Callable[[T, int, Stream[T]], Iterable[U]]) -> Stream[U]: ...
2211    def flat_map(self, transform: Callable[..., Iterable[U]]) -> Stream[U]:
2212        """
2213        Returns a single list of all elements yielded from results of [transform]
2214        function being invoked on each element of original collection.
2215
2216        Example 1:
2217        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2218        >>> it(lst).flat_map(lambda x: x).to_list()
2219        ['a', 'b', 'c', 'd', 'e']
2220        """
2221        return self.map(transform).flatten()
2222
2223    def flatten(self: Iterable[Iterable[U]]) -> Stream[U]:
2224        """
2225        Returns a sequence of all elements from all sequences in this sequence.
2226
2227        Example 1:
2228        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2229        >>> it(lst).flatten().to_list()
2230        ['a', 'b', 'c', 'd', 'e']
2231        """
2232        from .flattening import FlatteningTransform
2233
2234        return it(FlatteningTransform(self))
2235
2236    @overload
2237    def group_by(self, key_selector: Callable[[T], K]) -> Stream[Grouping[K, T]]: ...
2238    @overload
2239    def group_by(self, key_selector: Callable[[T, int], K]) -> Stream[Grouping[K, T]]: ...
2240    @overload
2241    def group_by(
2242        self, key_selector: Callable[[T, int, Stream[T]], K]
2243    ) -> Stream[Grouping[K, T]]: ...
2244    def group_by(self, key_selector: Callable[..., K]) -> Stream[Grouping[K, T]]:
2245        """
2246        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2247        and values being the corresponding elements of original collection.
2248
2249        Example 1:
2250        >>> lst = [1, 2, 3, 4, 5]
2251        >>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list()
2252        [(1, [1, 3, 5]), (0, [2, 4])]
2253        """
2254        from .grouping import GroupingTransform
2255
2256        return it(GroupingTransform(self, self.__callback_overload_warpper__(key_selector)))
2257
2258    @overload
2259    def group_by_to(
2260        self, destination: Dict[K, List[T]], key_selector: Callable[[T], K]
2261    ) -> Dict[K, List[T]]: ...
2262    @overload
2263    def group_by_to(
2264        self, destination: Dict[K, List[T]], key_selector: Callable[[T, int], K]
2265    ) -> Dict[K, List[T]]: ...
2266    @overload
2267    def group_by_to(
2268        self,
2269        destination: Dict[K, List[T]],
2270        key_selector: Callable[[T, int, Stream[T]], K],
2271    ) -> Dict[K, List[T]]: ...
2272    def group_by_to(
2273        self, destination: Dict[K, List[T]], key_selector: Callable[..., K]
2274    ) -> Dict[K, List[T]]:
2275        """
2276        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2277        and values being the corresponding elements of original collection.
2278
2279        Example 1:
2280        >>> lst = [1, 2, 3, 4, 5]
2281        >>> it(lst).group_by_to({}, lambda x: x%2)
2282        {1: [1, 3, 5], 0: [2, 4]}
2283        """
2284        key_selector = self.__callback_overload_warpper__(key_selector)
2285        for e in self:
2286            k = key_selector(e)
2287            if k not in destination:
2288                destination[k] = []
2289            destination[k].append(e)
2290        return destination
2291
2292    @overload
2293    def for_each(self, action: Callable[[T], None]) -> None: ...
2294    @overload
2295    def for_each(self, action: Callable[[T, int], None]) -> None: ...
2296    @overload
2297    def for_each(self, action: Callable[[T, int, Stream[T]], None]) -> None: ...
2298    def for_each(self, action: Callable[..., None]) -> None:
2299        """
2300        Invokes [action] function on each element of the given Stream.
2301
2302        Example 1:
2303        >>> lst = ['a', 'b', 'c']
2304        >>> it(lst).for_each(lambda x: print(x))
2305        a
2306        b
2307        c
2308
2309        Example 2:
2310        >>> lst = ['a', 'b', 'c']
2311        >>> it(lst).for_each(lambda x, i: print(x, i))
2312        a 0
2313        b 1
2314        c 2
2315        """
2316        self.on_each(action)
2317
2318    @overload
2319    def parallel_for_each(
2320        self, action: Callable[[T], None], max_workers: Optional[int] = None
2321    ) -> None: ...
2322    @overload
2323    def parallel_for_each(
2324        self, action: Callable[[T, int], None], max_workers: Optional[int] = None
2325    ) -> None: ...
2326    @overload
2327    def parallel_for_each(
2328        self,
2329        action: Callable[[T, int, Stream[T]], None],
2330        max_workers: Optional[int] = None,
2331    ) -> None: ...
2332    def parallel_for_each(
2333        self, action: Callable[..., None], max_workers: Optional[int] = None
2334    ) -> None:
2335        """
2336        Invokes [action] function on each element of the given Stream in parallel.
2337
2338        Example 1:
2339        >>> lst = ['a', 'b', 'c']
2340        >>> it(lst).parallel_for_each(lambda x: print(x))
2341        a
2342        b
2343        c
2344
2345        Example 2:
2346        >>> lst = ['a', 'b', 'c']
2347        >>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2)
2348        a
2349        b
2350        c
2351        """
2352        self.parallel_on_each(action, max_workers)
2353
2354    @overload
2355    def on_each(self, action: Callable[[T], None]) -> Stream[T]: ...
2356    @overload
2357    def on_each(self, action: Callable[[T, int], None]) -> Stream[T]: ...
2358    @overload
2359    def on_each(self, action: Callable[[T, int, Stream[T]], None]) -> Stream[T]: ...
2360    def on_each(self, action: Callable[..., None]) -> Stream[T]:
2361        """
2362        Invokes [action] function on each element of the given Stream.
2363
2364        Example 1:
2365        >>> lst = ['a', 'b', 'c']
2366        >>> it(lst).on_each(lambda x: print(x)) and None
2367        a
2368        b
2369        c
2370
2371        Example 2:
2372        >>> lst = ['a', 'b', 'c']
2373        >>> it(lst).on_each(lambda x, i: print(x, i)) and None
2374        a 0
2375        b 1
2376        c 2
2377        """
2378        action = self.__callback_overload_warpper__(action)
2379        for i in self:
2380            action(i)
2381        return self
2382
2383    @overload
2384    def parallel_on_each(
2385        self,
2386        action: Callable[[T], None],
2387        max_workers: Optional[int] = None,
2388        chunksize: int = 1,
2389        executor: "ParallelMappingTransform.Executor" = "Thread",
2390    ) -> Stream[T]: ...
2391    @overload
2392    def parallel_on_each(
2393        self,
2394        action: Callable[[T, int], None],
2395        max_workers: Optional[int] = None,
2396        chunksize: int = 1,
2397        executor: "ParallelMappingTransform.Executor" = "Thread",
2398    ) -> Stream[T]: ...
2399    @overload
2400    def parallel_on_each(
2401        self,
2402        action: Callable[[T, int, Stream[T]], None],
2403        max_workers: Optional[int] = None,
2404        chunksize: int = 1,
2405        executor: "ParallelMappingTransform.Executor" = "Thread",
2406    ) -> Stream[T]: ...
2407    def parallel_on_each(
2408        self,
2409        action: Callable[..., None],
2410        max_workers: Optional[int] = None,
2411        chunksize: int = 1,
2412        executor: "ParallelMappingTransform.Executor" = "Thread",
2413    ) -> Stream[T]:
2414        """
2415        Invokes [action] function on each element of the given Stream.
2416
2417        Example 1:
2418        >>> lst = ['a', 'b', 'c']
2419        >>> it(lst).parallel_on_each(lambda x: print(x)) and None
2420        a
2421        b
2422        c
2423
2424        Example 2:
2425        >>> lst = ['a', 'b', 'c']
2426        >>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None
2427        a
2428        b
2429        c
2430        """
2431        from .parallel_mapping import ParallelMappingTransform
2432
2433        action = self.__callback_overload_warpper__(action)
2434        for _ in ParallelMappingTransform(self, action, max_workers, chunksize, executor):
2435            pass
2436        return self
2437
2438    @overload
2439    def zip(self, other: Iterable[U]) -> Stream[Tuple[T, U]]: ...
2440    @overload
2441    def zip(self, other: Iterable[U], transform: Callable[[T, U], V]) -> Stream[V]: ...
2442    def zip(
2443        self,
2444        other: Iterable[Any],
2445        transform: Optional[Callable[..., V]] = None,  # type: ignore
2446    ) -> Stream[Any]:
2447        """
2448        Returns a new Stream of tuples, where each tuple contains two elements.
2449
2450        Example 1:
2451        >>> lst1 = ['a', 'b', 'c']
2452        >>> lst2 = [1, 2, 3]
2453        >>> it(lst1).zip(lst2).to_list()
2454        [('a', 1), ('b', 2), ('c', 3)]
2455
2456        Example 2:
2457        >>> lst1 = ['a', 'b', 'c']
2458        >>> lst2 = [1, 2, 3]
2459        >>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list()
2460        ['a__1', 'b__2', 'c__3']
2461        """
2462        if transform is None:
2463
2464            def transform(*x: Any) -> Tuple[Any, ...]:
2465                return (*x,)
2466
2467        from .merging import MergingTransform
2468
2469        return it(MergingTransform(self, other, transform))
2470
2471    @overload
2472    def zip_with_next(self) -> Stream[Tuple[T, T]]: ...
2473    @overload
2474    def zip_with_next(self, transform: Callable[[T, T], V]) -> Stream[V]: ...
2475    def zip_with_next(self, transform: Optional[Callable[[T, T], Any]] = None) -> Stream[Any]:
2476        """
2477        Returns a sequence containing the results of applying the given [transform] function
2478        to an each pair of two adjacent elements in this sequence.
2479
2480        Example 1:
2481        >>> lst = ['a', 'b', 'c']
2482        >>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list()
2483        ['a__b', 'b__c']
2484
2485        Example 2:
2486        >>> lst = ['a', 'b', 'c']
2487        >>> it(lst).zip_with_next().to_list()
2488        [('a', 'b'), ('b', 'c')]
2489        """
2490        from .merging_with_next import MergingWithNextTransform
2491
2492        return it(MergingWithNextTransform(self, transform or (lambda a, b: (a, b))))
2493
2494    @overload
2495    def unzip(self: Stream[Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ...
2496    @overload
2497    def unzip(self, transform: Callable[[T], Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ...
2498    @overload
2499    def unzip(
2500        self, transform: Callable[[T, int], Tuple[U, V]]
2501    ) -> "Tuple[ListLike[U], ListLike[V]]": ...
2502    @overload
2503    def unzip(
2504        self, transform: Callable[[T, int, Stream[T]], Tuple[U, V]]
2505    ) -> "Tuple[ListLike[U], ListLike[V]]": ...
2506    def unzip(  # type: ignore
2507        self: Stream[Tuple[U, V]],
2508        transform: Union[Optional[Callable[..., Tuple[Any, Any]]], bool] = None,
2509    ) -> "Tuple[ListLike[U], ListLike[V]]":
2510        """
2511        Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array.
2512
2513        Example 1:
2514        >>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}]
2515        >>> a, b = it(lst).unzip(lambda x: (x['name'], x['age']))
2516        >>> a
2517        ['a', 'b', 'c']
2518        >>> b
2519        [11, 12, 13]
2520
2521        Example 1:
2522        >>> lst = [('a', 11), ('b', 12), ('c', 13)]
2523        >>> a, b = it(lst).unzip()
2524        >>> a
2525        ['a', 'b', 'c']
2526        >>> b
2527        [11, 12, 13]
2528        """
2529        from .list_like import ListLike
2530
2531        it = self
2532        if isinstance(transform, bool):
2533            transform = None
2534
2535        if transform is not None:
2536            transform = self.__callback_overload_warpper__(transform)
2537            it = it.map(transform)
2538
2539        a = it.map(lambda x: x[0])  # type: ignore
2540        b = it.map(lambda x: x[1])  # type: ignore
2541
2542        return ListLike(a), ListLike(b)
2543
2544    def with_index(self) -> Stream[IndexedValue[T]]:
2545        """
2546        Returns a sequence containing the elements of this sequence and their indexes.
2547
2548        Example 1:
2549        >>> lst = ['a', 'b', 'c']
2550        >>> it(lst).with_index().to_list()
2551        [IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)]
2552        """
2553        return self.indexed()
2554
2555    @overload
2556    def shuffled(self) -> Stream[T]: ...
2557    @overload
2558    def shuffled(self, seed: Union[int, float, str, bytes, bytearray, None]) -> Stream[T]: ...
2559    @overload
2560    def shuffled(self, random: "Random") -> Stream[T]: ...
2561    def shuffled(  # type: ignore
2562        self, seed: Union["Random", int, float, str, bytes, bytearray, None] = None
2563    ) -> Stream[T]:
2564        """
2565        Returns a sequence that yields elements of this sequence randomly shuffled
2566        using the specified [random] instance as the source of randomness.
2567
2568        Example 1:
2569        >>> lst = ['a', 'b', 'c']
2570        >>> it(lst).shuffled('123').to_list()
2571        ['b', 'a', 'c']
2572
2573        Example 2:
2574        >>> from random import Random
2575        >>> lst = ['a', 'b', 'c']
2576        >>> it(lst).shuffled(Random('123')).to_list()
2577        ['b', 'a', 'c']
2578
2579        Example 3:
2580        >>> lst = ['a', 'b', 'c']
2581        >>> it(lst).shuffled(123).to_list()
2582        ['c', 'b', 'a']
2583        """
2584        from .shuffling import ShufflingTransform
2585
2586        return it(ShufflingTransform(self, seed))
2587
2588    @overload
2589    def partition(self, predicate: Callable[[T], bool]) -> "Tuple[ListLike[T], ListLike[T]]": ...
2590    @overload
2591    def partition(
2592        self, predicate: Callable[[T, int], bool]
2593    ) -> "Tuple[ListLike[T], ListLike[T]]": ...
2594    @overload
2595    def partition(
2596        self, predicate: Callable[[T, int, Stream[T]], bool]
2597    ) -> "Tuple[ListLike[T], ListLike[T]]": ...
2598    def partition(self, predicate: Callable[..., bool]) -> "Tuple[ListLike[T], ListLike[T]]":
2599        """
2600        Partitions the elements of the given Stream into two groups,
2601        the first group containing the elements for which the predicate returns true,
2602        and the second containing the rest.
2603
2604        Example 1:
2605        >>> lst = ['a', 'b', 'c', '2']
2606        >>> it(lst).partition(lambda x: x.isalpha())
2607        (['a', 'b', 'c'], ['2'])
2608
2609        Example 2:
2610        >>> lst = ['a', 'b', 'c', '2']
2611        >>> it(lst).partition(lambda _, i: i % 2 == 0)
2612        (['a', 'c'], ['b', '2'])
2613        """
2614        from .list_like import ListLike
2615
2616        predicate_a = self.__callback_overload_warpper__(predicate)
2617        predicate_b = self.__callback_overload_warpper__(predicate)
2618        part_a = self.filter(predicate_a)
2619        part_b = self.filter(lambda x: not predicate_b(x))
2620        return ListLike(part_a), ListLike(part_b)
2621
2622    def indexed(self) -> Stream[IndexedValue[T]]:
2623        return self.map(lambda x, i: IndexedValue(x, i))
2624
2625    @overload
2626    def combinations(self, n: Literal[2]) -> Stream[Tuple[T, T]]: ...
2627    @overload
2628    def combinations(self, n: Literal[3]) -> Stream[Tuple[T, T, T]]: ...
2629    @overload
2630    def combinations(self, n: Literal[4]) -> Stream[Tuple[T, T, T, T]]: ...
2631    @overload
2632    def combinations(self, n: Literal[5]) -> Stream[Tuple[T, T, T, T, T]]: ...
2633    def combinations(self, n: int) -> Stream[Tuple[T, ...]]:
2634        """
2635        Returns a Stream of all possible combinations of size [n] from the given Stream.
2636
2637        Example 1:
2638        >>> lst = ['a', 'b', 'c']
2639        >>> it(lst).combinations(2).to_list()
2640        [('a', 'b'), ('a', 'c'), ('b', 'c')]
2641        """
2642        from .combination import CombinationTransform
2643
2644        return it(CombinationTransform(self, n))
2645
2646    def nth(self, n: int) -> T:
2647        """
2648        Returns the nth element of the given Stream.
2649
2650        Example 1:
2651        >>> lst = ['a', 'b', 'c']
2652        >>> it(lst).nth(2)
2653        'c'
2654        """
2655        return self.skip(n).first()
2656
2657    def windowed(self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[List[T]]:
2658        """
2659         Returns a Stream of all possible sliding windows of size [size] from the given Stream.
2660
2661        Example 1:
2662        >>> lst = ['a', 'b', 'c', 'd', 'e']
2663        >>> it(lst).windowed(3).to_list()
2664        [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
2665
2666        Example 2:
2667        >>> lst = ['a', 'b', 'c', 'd', 'e']
2668        >>> it(lst).windowed(3, 2).to_list()
2669        [['a', 'b', 'c'], ['c', 'd', 'e']]
2670
2671        Example 3:
2672        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2673        >>> it(lst).windowed(3, 2, True).to_list()
2674        [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']]
2675        """
2676        from .windowed import WindowedTransform
2677
2678        return it(WindowedTransform(self, size, step, partialWindows))
2679
2680    def chunked(self, size: int) -> Stream[List[T]]:
2681        """
2682        Returns a Stream of all possible chunks of size [size] from the given Stream.
2683
2684        Example 1:
2685        >>> lst = ['a', 'b', 'c', 'd', 'e']
2686        >>> it(lst).chunked(3).to_list()
2687        [['a', 'b', 'c'], ['d', 'e']]
2688
2689
2690        Example 2:
2691        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2692        >>> it(lst).chunked(3).to_list()
2693        [['a', 'b', 'c'], ['d', 'e', 'f']]
2694        """
2695        return self.windowed(size, size, True)
2696
2697    def repeat(self, n: int) -> Stream[T]:
2698        """
2699        Returns a Stream containing this sequence repeated n times.
2700
2701        Example 1:
2702        >>> lst = ['a', 'b']
2703        >>> it(lst).repeat(3).to_list()
2704        ['a', 'b', 'a', 'b', 'a', 'b']
2705        """
2706        from .concat import ConcatTransform
2707
2708        return it(ConcatTransform([self] * n))
2709
2710    def concat(self, *other: Iterable[T]) -> Stream[T]:
2711        """
2712        Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream.
2713
2714        Example 1:
2715        >>> lst1 = ['a', 'b', 'c']
2716        >>> lst2 = [1, 2, 3]
2717        >>> it(lst1).concat(lst2).to_list()
2718        ['a', 'b', 'c', 1, 2, 3]
2719
2720        Example 2:
2721        >>> lst1 = ['a', 'b', 'c']
2722        >>> lst2 = [1, 2, 3]
2723        >>> lst3 = [4, 5, 6]
2724        >>> it(lst1).concat(lst2, lst3).to_list()
2725        ['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
2726        """
2727        from .concat import ConcatTransform
2728
2729        return it(ConcatTransform([self, *other]))
2730
2731    def intersect(self, *other: Iterable[T]) -> Stream[T]:
2732        """
2733        Returns a set containing all elements that are contained by both this collection and the specified collection.
2734
2735        The returned set preserves the element iteration order of the original collection.
2736
2737        To get a set containing all elements that are contained at least in one of these collections use union.
2738
2739        Example 1:
2740        >>> lst1 = ['a', 'b', 'c']
2741        >>> lst2 = ['a2', 'b2', 'c']
2742        >>> it(lst1).intersect(lst2).to_list()
2743        ['c']
2744
2745        Example 2:
2746        >>> lst1 = ['a', 'b', 'c']
2747        >>> lst2 = ['a2', 'b', 'c']
2748        >>> lst3 = ['a3', 'b', 'c3']
2749        >>> it(lst1).intersect(lst2, lst3).to_list()
2750        ['b']
2751
2752
2753        Example 1:
2754        >>> lst1 = ['a', 'a', 'c']
2755        >>> lst2 = ['a2', 'b2', 'a']
2756        >>> it(lst1).intersect(lst2).to_list()
2757        ['a']
2758        """
2759        from .intersection import IntersectionTransform
2760
2761        return it(IntersectionTransform([self, *other]))
2762
2763    def union(self, *other: Stream[T]) -> Stream[T]:
2764        """
2765        Returns a set containing all distinct elements from both collections.
2766
2767        The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.
2768
2769        To get a set containing all elements that are contained in both collections use intersect.
2770
2771        Example 1:
2772        >>> lst1 = ['a', 'b', 'c']
2773        >>> lst2 = ['a2', 'b2', 'c']
2774        >>> it(lst1).union(lst2).to_list()
2775        ['a', 'b', 'c', 'a2', 'b2']
2776
2777        Example 2:
2778        >>> lst1 = ['a', 'b', 'c']
2779        >>> lst2 = ['a2', 'b', 'c']
2780        >>> lst3 = ['a3', 'b', 'c3']
2781        >>> it(lst1).union(lst2, lst3).to_list()
2782        ['a', 'b', 'c', 'a2', 'a3', 'c3']
2783
2784
2785        Example 1:
2786        >>> lst1 = ['a', 'a', 'c']
2787        >>> lst2 = ['a2', 'b2', 'a']
2788        >>> it(lst1).union(lst2).to_list()
2789        ['a', 'c', 'a2', 'b2']
2790        """
2791        return self.concat(*other).distinct()
2792
2793    def join(self: Stream[str], separator: str = " ") -> str:
2794        """
2795        Joins the elements of the given Stream into a string.
2796
2797        Example 1:
2798        >>> lst = ['a', 'b', 'c']
2799        >>> it(lst).join(', ')
2800        'a, b, c'
2801        """
2802        return separator.join(self)
2803
2804    @overload
2805    def progress(self) -> Stream[T]: ...
2806    @overload
2807    def progress(
2808        self, progress_func: Union[Literal["tqdm"], Literal["tqdm_rich"]]
2809    ) -> Stream[T]: ...
2810    @overload
2811    def progress(self, progress_func: Callable[[Stream[T]], Iterable[T]]) -> Stream[T]: ...
2812    def progress(
2813        self,
2814        progress_func: Union[
2815            Callable[[Stream[T]], Iterable[T]],
2816            Literal["tqdm"],
2817            Literal["tqdm_rich"],
2818            None,
2819        ] = None,
2820    ) -> Stream[T]:
2821        """
2822        Returns a Stream that enable a progress bar for the given Stream.
2823
2824        Example 1:
2825        >>> from tqdm import tqdm
2826        >>> from time import sleep
2827        >>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None
2828        >>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass
2829        """
2830        if progress_func is not None and callable(progress_func):
2831            return it(progress_func(self))
2832
2833        def import_tqdm():
2834            if progress_func == "tqdm_rich":
2835                import warnings
2836                from tqdm.rich import tqdm
2837                from tqdm import TqdmExperimentalWarning
2838
2839                warnings.filterwarnings("ignore", category=TqdmExperimentalWarning)
2840            else:
2841                from tqdm import tqdm
2842            return tqdm
2843
2844        try:
2845            tqdm = import_tqdm()
2846        except ImportError:
2847            from pip import main as pip  # type: ignore
2848
2849            pip(["install", "tqdm"])
2850            tqdm = import_tqdm()
2851
2852        return it(tqdm(self, total=len(self)))
2853
2854    def typing_as(self, typ: Type[U]) -> Stream[U]:
2855        """
2856        Cast the element as specific Type to gain code completion base on type annotations.
2857        """
2858        el = self.first_not_none_of_or_none()
2859        if el is None or isinstance(el, typ) or not isinstance(el, dict):
2860            return self  # type: ignore
2861
2862        class AttrDict(Dict[str, Any]):
2863            def __init__(self, value: Dict[str, Any]) -> None:
2864                super().__init__(**value)
2865                setattr(self, "__dict__", value)
2866                self.__getattr__ = value.__getitem__
2867                self.__setattr__ = value.__setattr__  # type: ignore
2868
2869        return self.map(AttrDict)  # type: ignore  # use https://github.com/cdgriffith/Box ?
2870
2871    def to_set(self) -> Set[T]:
2872        """
2873        Returns a set containing all elements of this Stream.
2874
2875        Example 1:
2876        >>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'}
2877        True
2878        """
2879        return set(self)
2880
2881    @overload
2882    def to_dict(self: Stream[Tuple[K, V]]) -> Dict[K, V]: ...
2883    @overload
2884    def to_dict(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ...
2885    @overload
2886    def to_dict(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ...
2887    @overload
2888    def to_dict(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ...
2889    def to_dict(self, transform: Optional[Callable[..., Tuple[K, V]]] = None) -> Dict[K, V]:
2890        """
2891        Returns a [Dict] containing key-value Tuple provided by [transform] function
2892        applied to elements of the given Stream.
2893
2894        Example 1:
2895        >>> lst = ['1', '2', '3']
2896        >>> it(lst).to_dict(lambda x: (int(x), x))
2897        {1: '1', 2: '2', 3: '3'}
2898
2899        Example 2:
2900        >>> lst = [(1, '1'), (2, '2'), (3, '3')]
2901        >>> it(lst).to_dict()
2902        {1: '1', 2: '2', 3: '3'}
2903        """
2904        return self.associate(transform or (lambda x: x))  # type: ignore
2905
2906    def to_list(self) -> List[T]:
2907        """
2908        Returns a list with elements of the given Stream.
2909
2910        Example 1:
2911        >>> it(['b', 'c', 'a']).to_list()
2912        ['b', 'c', 'a']
2913        """
2914        if self.__transform__.cache is not None:
2915            return self.__transform__.cache.copy()
2916        return [s for s in self]
2917
2918    async def to_list_async(self: Iterable[Awaitable[T]]) -> List[T]:
2919        """
2920        Returns a list with elements of the given Stream.
2921
2922        Example 1:
2923        >>> it(['b', 'c', 'a']).to_list()
2924        ['b', 'c', 'a']
2925        """
2926        from asyncio import gather
2927
2928        return await gather(*self)  # type: ignore
2929
2930    def let(self, block: Callable[[Stream[T]], U]) -> U:
2931        """
2932        Calls the specified function [block] with `self` value as its argument and returns its result.
2933
2934        Example 1:
2935        >>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list()
2936        ['a!', 'b!', 'c!']
2937        """
2938        return block(self)
2939
2940    def also(self, block: Callable[[Stream[T]], Any]) -> Stream[T]:
2941        """
2942        Calls the specified function [block] with `self` value as its argument and returns `self` value.
2943
2944        Example 1:
2945        >>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list()
2946        ['a', 'b', 'c']
2947        """
2948        block(self)
2949        return self
2950
2951    @property
2952    def size(self) -> int:
2953        """
2954        Returns the size of the given Stream.
2955        """
2956        return len(self.data)
2957
2958    def is_empty(self) -> bool:
2959        """
2960        Returns True if the Stream is empty, False otherwise.
2961
2962        Example 1:
2963        >>> it(['a', 'b', 'c']).is_empty()
2964        False
2965
2966        Example 2:
2967        >>> it([None]).is_empty()
2968        False
2969
2970        Example 3:
2971        >>> it([]).is_empty()
2972        True
2973        """
2974        return id(self.first_or_default(self)) == id(self)
2975
2976    def __iter__(self) -> Iterator[T]:
2977        return self.__do_iter__()
2978
2979    def iter(self) -> Iterator[T]:
2980        return self.__do_iter__()
2981
2982    def __do_iter__(self) -> Iterator[T]:
2983        yield from self.__transform__
2984
2985    def __len__(self) -> int:
2986        return len(self.__transform__)
2987
2988    def __bool__(self) -> bool:
2989        return not self.is_empty()
2990
2991    def __repr__(self) -> str:
2992        if self.__transform__.cache is None:
2993            return "[...]"
2994        return repr(self.to_list())
2995
2996    def __getitem__(self, key: int) -> T:
2997        """
2998        Returns the element at the specified [index] in the Stream.
2999
3000        Example 1:
3001        >>> lst = [1, 2, 3]
3002        >>> it(lst)[1]
3003        2
3004
3005        Example 2:
3006        >>> lst = [1, 2, 3]
3007        >>> it(lst)[3]
3008        Traceback (most recent call last):
3009        ...
3010        IndexError: Index 3 out of range
3011        """
3012        return self.element_at(key)
3013
3014    @overload
3015    def __callback_overload_warpper__(self, callback: Callable[[T], U]) -> Callable[[T], U]: ...
3016    @overload
3017    def __callback_overload_warpper__(
3018        self, callback: Callable[[T, int], U]
3019    ) -> Callable[[T], U]: ...
3020    @overload
3021    def __callback_overload_warpper__(
3022        self, callback: Callable[[T, int, Stream[T]], U]
3023    ) -> Callable[[T], U]: ...
3024    def __callback_overload_warpper__(self, callback: Callable[..., U]) -> Callable[[T], U]:
3025        if hasattr(callback, "__code__"):
3026            if callback.__code__.co_argcount == 2:
3027                index = AutoIncrementIndex()
3028                return lambda x: callback(x, index())
3029            if callback.__code__.co_argcount == 3:
3030                index = AutoIncrementIndex()
3031                return lambda x: callback(x, index(), self)
3032        return callback

Given an [iterator] function constructs a [Stream] that returns values through the [Iterator] provided by that function.

The values are evaluated lazily, and the sequence is potentially infinite.

Stream(iterable: Union[Iterable[~T], pyiter.transform.Transform[Any, ~T]])
60    def __init__(self, iterable: Union[Iterable[T], Transform[Any, T]]) -> None:
61        super().__init__()
62
63        self.__transform__ = new_transform(iterable)
transforms: Iterable[pyiter.transform.Transform[Any, Any]]
65    @cached_property
66    def transforms(self) -> Iterable[Transform[Any, Any]]:
67        return [*self.__transform__.transforms()]
data: List[~T]
69    @property
70    def data(self) -> List[T]:
71        if self.__transform__.cache is not None:
72            return self.__transform__.cache.copy()
73        if is_debugging():
74            raise LazyEvaluationException("The sequence has not been evaluated yet.")
75        return self.to_list()
def dedup(self) -> Stream[~T]:
77    def dedup(self) -> Stream[T]:
78        """
79        Removes consecutive repeated elements in the sequence.
80
81        If the sequence is sorted, this removes all duplicates.
82
83        Example 1:
84        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
85        >>> it(lst).dedup().to_list()
86        ['a1', 'b2', 'a2', 'a1']
87
88        Example 1:
89        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
90        >>> it(lst).sorted().dedup().to_list()
91        ['a1', 'a2', 'b2']
92        """
93        return self.dedup_by(lambda x: x)

Removes consecutive repeated elements in the sequence.

If the sequence is sorted, this removes all duplicates.

Example 1:

>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst)pyiter.dedup().to_list()
['a1', 'b2', 'a2', 'a1']

Example 1:

>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).sorted()pyiter.dedup().to_list()
['a1', 'a2', 'b2']
def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[~T]:
101    def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
102        """
103        Removes all but the first of consecutive elements in the sequence that resolve to the same key.
104        """
105        return self.dedup_into_group_by(key_selector).map(lambda x: x[0])

Removes all but the first of consecutive elements in the sequence that resolve to the same key.

def dedup_with_count_by( self, key_selector: Callable[..., Any]) -> Stream[typing.Tuple[~T, int]]:
117    def dedup_with_count_by(self, key_selector: Callable[..., Any]) -> Stream[Tuple[T, int]]:
118        """
119        Removes all but the first of consecutive elements and its count that resolve to the same key.
120
121        Example 1:
122        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
123        >>> it(lst).dedup_with_count_by(lambda x: x).to_list()
124        [('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)]
125
126        Example 1:
127        >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
128        >>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list()
129        [('a1', 3), ('a2', 1), ('b2', 1)]
130        """
131        return self.dedup_into_group_by(key_selector).map(lambda x: (x[0], len(x)))

Removes all but the first of consecutive elements and its count that resolve to the same key.

Example 1:

>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).dedup_with_count_by(lambda x: x).to_list()
[('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)]

Example 1:

>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list()
[('a1', 3), ('a2', 1), ('b2', 1)]
def dedup_into_group_by( self, key_selector: Callable[..., Any]) -> Stream[typing.List[~T]]:
141    def dedup_into_group_by(self, key_selector: Callable[..., Any]) -> Stream[List[T]]:
142        from .dedup import DedupTransform
143
144        return it(DedupTransform(self, key_selector))
def filter(self, predicate: Callable[..., bool]) -> Stream[~T]:
152    def filter(self, predicate: Callable[..., bool]) -> Stream[T]:
153        """
154        Returns a Stream containing only elements matching the given [predicate].
155
156        Example 1:
157        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
158        >>> it(lst).filter(lambda x: x.startswith('a')).to_list()
159        ['a1', 'a2']
160
161        Example 2:
162        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
163        >>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list()
164        ['a1', 'b2', 'a2']
165        """
166        from .filtering import FilteringTransform
167
168        return it(FilteringTransform(self, self.__callback_overload_warpper__(predicate)))

Returns a Stream containing only elements matching the given [predicate].

Example 1:

>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter(lambda x: x.startswith('a')).to_list()
['a1', 'a2']

Example 2:

>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list()
['a1', 'b2', 'a2']
def filter_is_instance(self, typ: Type[~U]) -> Stream[~U]:
170    def filter_is_instance(self, typ: Type[U]) -> Stream[U]:
171        """
172        Returns a Stream containing all elements that are instances of specified type parameter typ.
173
174        Example 1:
175        >>> lst = [ 'a1', 1, 'b2', 3]
176        >>> it(lst).filter_is_instance(int).to_list()
177        [1, 3]
178
179        """
180        from .type_guard import TypeGuardTransform, TypeGuard
181
182        def guard(x: T) -> TypeGuard[U]:
183            return isinstance(x, typ)
184
185        return it(TypeGuardTransform(self, guard))

Returns a Stream containing all elements that are instances of specified type parameter typ.

Example 1:

>>> lst = [ 'a1', 1, 'b2', 3]
>>> it(lst).filter_is_instance(int).to_list()
[1, 3]
def filter_not(self, predicate: Callable[..., bool]) -> Stream[~T]:
193    def filter_not(self, predicate: Callable[..., bool]) -> Stream[T]:
194        """
195        Returns a Stream containing all elements not matching the given [predicate].
196
197        Example 1:
198        >>> lst = [ 'a1', 'b1', 'b2', 'a2']
199        >>> it(lst).filter_not(lambda x: x.startswith('a')).to_list()
200        ['b1', 'b2']
201
202        Example 2:
203        >>> lst = [ 'a1', 'a2', 'b1', 'b2']
204        >>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list()
205        ['a2', 'b1', 'b2']
206        """
207        predicate = self.__callback_overload_warpper__(predicate)
208        return self.filter(lambda x: not predicate(x))

Returns a Stream containing all elements not matching the given [predicate].

Example 1:

>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter_not(lambda x: x.startswith('a')).to_list()
['b1', 'b2']

Example 2:

>>> lst = [ 'a1', 'a2', 'b1', 'b2']
>>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list()
['a2', 'b1', 'b2']
def filter_not_none( self: Stream[typing.Optional[~U]]) -> Stream[~U]:
214    def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]:
215        """
216        Returns a Stream containing all elements that are not `None`.
217
218        Example 1:
219        >>> lst = [ 'a', None, 'b']
220        >>> it(lst).filter_not_none().to_list()
221        ['a', 'b']
222        """
223        from .type_guard import TypeGuardTransform, TypeGuard
224
225        def guard(x: Optional[U]) -> TypeGuard[U]:
226            return x is not None
227
228        return it(TypeGuardTransform(self, guard))

Returns a Stream containing all elements that are not None.

Example 1:

>>> lst = [ 'a', None, 'b']
>>> it(lst).filter_not_none().to_list()
['a', 'b']
def map( self, transform: Callable[..., ~U], return_exceptions: bool = False) -> Union[Stream[~U], Stream[Union[~U, BaseException]]]:
258    def map(
259        self, transform: Callable[..., U], return_exceptions: bool = False
260    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
261        """
262        Returns a Stream containing the results of applying the given [transform] function
263        to each element in the original Stream.
264
265        Example 1:
266        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
267        >>> it(lst).map(lambda x: x['age']).to_list()
268        [12, 13]
269
270        Example 2:
271        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
272        >>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list()
273        ['A0', 'B1']
274
275        Example 3:
276        >>> lst = ['hi', 'abc']
277        >>> it(lst).map(len).to_list()
278        [2, 3]
279        """
280        from .mapping import MappingTransform
281
282        transform = self.__callback_overload_warpper__(transform)
283        if return_exceptions:
284
285            def transform_wrapper(x: T) -> Union[U, BaseException]:
286                try:
287                    return transform(x)
288                except BaseException as e:
289                    return e
290
291            return it(MappingTransform(self, transform_wrapper))
292
293        return it(MappingTransform(self, transform))

Returns a Stream containing the results of applying the given [transform] function to each element in the original Stream.

Example 1:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).map(lambda x: x['age']).to_list()
[12, 13]

Example 2:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list()
['A0', 'B1']

Example 3:

>>> lst = ['hi', 'abc']
>>> it(lst).map(len).to_list()
[2, 3]
async def map_async( self, transform: Callable[..., Awaitable[~U]], return_exceptions: bool = False) -> Union[Stream[~U], Stream[Union[~U, BaseException]]]:
309    async def map_async(
310        self, transform: Callable[..., Awaitable[U]], return_exceptions: bool = False
311    ) -> Union[Stream[U], Stream[Union[U, BaseException]]]:
312        """
313        Similar to `.map()` but you can input a async transform then await it.
314        """
315        from asyncio import gather
316
317        if return_exceptions:
318            return it(await gather(*self.map(transform), return_exceptions=True))
319        return it(await gather(*self.map(transform)))

Similar to .map() but you can input a async transform then await it.

def map_not_none(self, transform: Callable[..., Optional[~U]]) -> Stream[~U]:
327    def map_not_none(self, transform: Callable[..., Optional[U]]) -> Stream[U]:
328        """
329        Returns a Stream containing only the non-none results of applying the given [transform] function
330        to each element in the original collection.
331
332        Example 1:
333        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}]
334        >>> it(lst).map_not_none(lambda x: x['age']).to_list()
335        [12]
336        """
337        return self.map(transform).filter_not_none()  # type: ignore

Returns a Stream containing only the non-none results of applying the given [transform] function to each element in the original collection.

Example 1:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}]
>>> it(lst).map_not_none(lambda x: x['age']).to_list()
[12]
def parallel_map( self, transform: Callable[..., ~U], max_workers: Optional[int] = None, chunksize: int = 1, executor: 'ParallelMappingTransform.Executor' = 'Thread') -> Stream[~U]:
363    def parallel_map(
364        self,
365        transform: Callable[..., U],
366        max_workers: Optional[int] = None,
367        chunksize: int = 1,
368        executor: ParallelMappingTransform.Executor = "Thread",
369    ) -> Stream[U]:
370        """
371        Returns a Stream containing the results of applying the given [transform] function
372        to each element in the original Stream.
373
374        Example 1:
375        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
376        >>> it(lst).parallel_map(lambda x: x['age']).to_list()
377        [12, 13]
378
379        Example 2:
380        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
381        >>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list()
382        [12, 13]
383
384        Example 3:
385        >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
386        >>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list()
387        [12, 14]
388        """
389        from .parallel_mapping import ParallelMappingTransform
390
391        return it(
392            ParallelMappingTransform(
393                self,
394                self.__callback_overload_warpper__(transform),
395                max_workers,
396                chunksize,
397                executor,
398            )
399        )

Returns a Stream containing the results of applying the given [transform] function to each element in the original Stream.

Example 1:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x: x['age']).to_list()
[12, 13]

Example 2:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list()
[12, 13]

Example 3:

>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list()
[12, 14]
def find(self, predicate: Callable[..., bool]) -> Optional[~T]:
407    def find(self, predicate: Callable[..., bool]) -> Optional[T]:
408        """
409        Returns the first element matching the given [predicate], or `None` if no such element was found.
410
411        Example 1:
412        >>> lst = ['a', 'b', 'c']
413        >>> it(lst).find(lambda x: x == 'b')
414        'b'
415        """
416        return self.first_or_none(predicate)

Returns the first element matching the given [predicate], or None if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).find(lambda x: x == 'b')
'b'
def find_last(self, predicate: Callable[[~T], bool]) -> Optional[~T]:
418    def find_last(self, predicate: Callable[[T], bool]) -> Optional[T]:
419        """
420        Returns the last element matching the given [predicate], or `None` if no such element was found.
421
422        Example 1:
423        >>> lst = ['a', 'b', 'c']
424        >>> it(lst).find_last(lambda x: x == 'b')
425        'b'
426        """
427        return self.last_or_none(predicate)

Returns the last element matching the given [predicate], or None if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).find_last(lambda x: x == 'b')
'b'
def first(self, predicate: Optional[Callable[..., bool]] = None) -> ~T:
437    def first(self, predicate: Optional[Callable[..., bool]] = None) -> T:
438        """
439        Returns first element.
440
441        Example 1:
442        >>> lst = ['a', 'b', 'c']
443        >>> it(lst).first()
444        'a'
445
446        Example 2:
447        >>> lst = []
448        >>> it(lst).first()
449        Traceback (most recent call last):
450        ...
451        ValueError: Stream is empty.
452
453        Example 3:
454        >>> lst = ['a', 'b', 'c']
455        >>> it(lst).first(lambda x: x == 'b')
456        'b'
457
458        Example 4:
459        >>> lst = ['a', 'b', 'c']
460        >>> it(lst).first(lambda x: x == 'd')
461        Traceback (most recent call last):
462        ...
463        ValueError: Stream is empty.
464
465        Example 5:
466        >>> lst = [None]
467        >>> it(lst).first() is None
468        True
469        """
470        for e in self:
471            if predicate is None or predicate(e):
472                return e
473        raise ValueError("Stream is empty.")

Returns first element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first()
'a'

Example 2:

>>> lst = []
>>> it(lst).first()
Traceback (most recent call last):
...
ValueError: Stream is empty.

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first(lambda x: x == 'b')
'b'

Example 4:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first(lambda x: x == 'd')
Traceback (most recent call last):
...
ValueError: Stream is empty.

Example 5:

>>> lst = [None]
>>> it(lst).first() is None
True
def first_not_none_of( self: Stream[typing.Optional[~U]], transform: Optional[Callable[..., Optional[~U]]] = None) -> ~U:
491    def first_not_none_of(
492        self: Stream[Optional[U]],
493        transform: Optional[Callable[..., Optional[U]]] = None,
494    ) -> U:
495        """
496        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
497
498        Example 1:
499        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
500        >>> it(lst).first_not_none_of(lambda x: x['age'])
501        12
502
503        Example 2:
504        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
505        >>> it(lst).first_not_none_of(lambda x: x['age'])
506        Traceback (most recent call last):
507        ...
508        ValueError: No element of the Stream was transformed to a non-none value.
509        """
510
511        v = (
512            self.first_not_none_of_or_none()
513            if transform is None
514            else self.first_not_none_of_or_none(transform)
515        )
516        if v is None:
517            raise ValueError("No element of the Stream was transformed to a non-none value.")
518        return v

Returns the first non-None result of applying the given [transform] function to each element in the original collection.

Example 1:

>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
>>> it(lst).first_not_none_of(lambda x: x['age'])
12

Example 2:

>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
>>> it(lst).first_not_none_of(lambda x: x['age'])
Traceback (most recent call last):
...
ValueError: No element of the Stream was transformed to a non-none value.
def first_not_none_of_or_none(self, transform: Optional[Callable[..., ~T]] = None) -> Optional[~T]:
530    def first_not_none_of_or_none(
531        self, transform: Optional[Callable[..., T]] = None
532    ) -> Optional[T]:
533        """
534        Returns the first non-`None` result of applying the given [transform] function to each element in the original collection.
535
536        Example 1:
537        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
538        >>> it(lst).first_not_none_of_or_none(lambda x: x['age'])
539        12
540
541        Example 2:
542        >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
543        >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None
544        True
545        """
546        if transform is None:
547            return self.first_or_none()
548        return self.map_not_none(transform).first_or_none()

Returns the first non-None result of applying the given [transform] function to each element in the original collection.

Example 1:

>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
>>> it(lst).first_not_none_of_or_none(lambda x: x['age'])
12

Example 2:

>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
>>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None
True
def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[~T]:
558    def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
559        """
560        Returns the first element, or `None` if the Stream is empty.
561
562        Example 1:
563        >>> lst = []
564        >>> it(lst).first_or_none() is None
565        True
566
567        Example 2:
568        >>> lst = ['a', 'b', 'c']
569        >>> it(lst).first_or_none()
570        'a'
571
572        Example 2:
573        >>> lst = ['a', 'b', 'c']
574        >>> it(lst).first_or_none(lambda x: x == 'b')
575        'b'
576        """
577        if predicate is not None:
578            return self.first_or_default(predicate, None)
579        else:
580            return self.first_or_default(None)

Returns the first element, or None if the Stream is empty.

Example 1:

>>> lst = []
>>> it(lst).first_or_none() is None
True

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_none()
'a'

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_none(lambda x: x == 'b')
'b'
def first_or_default( self, predicate: Union[Callable[..., bool], ~U], default: Optional[~U] = None) -> Union[~T, ~U, NoneType]:
592    def first_or_default(  # type: ignore
593        self, predicate: Union[Callable[..., bool], U], default: Optional[U] = None
594    ) -> Union[T, U, None]:
595        """
596        Returns the first element, or the given [default] if the Stream is empty.
597
598        Example 1:
599        >>> lst = []
600        >>> it(lst).first_or_default('a')
601        'a'
602
603        Example 2:
604        >>> lst = ['b']
605        >>> it(lst).first_or_default('a')
606        'b'
607
608        Example 3:
609        >>> lst = ['a', 'b', 'c']
610        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
611        'b'
612
613        Example 4:
614        >>> lst = []
615        >>> it(lst).first_or_default(lambda x: x == 'b', 'd')
616        'd'
617        """
618        seq = self
619        if isinstance(predicate, Callable):
620            seq = self.filter(predicate)  # type: ignore
621        else:
622            default = predicate
623        return next(iter(seq), default)

Returns the first element, or the given [default] if the Stream is empty.

Example 1:

>>> lst = []
>>> it(lst).first_or_default('a')
'a'

Example 2:

>>> lst = ['b']
>>> it(lst).first_or_default('a')
'b'

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_default(lambda x: x == 'b', 'd')
'b'

Example 4:

>>> lst = []
>>> it(lst).first_or_default(lambda x: x == 'b', 'd')
'd'
def last(self, predicate: Optional[Callable[..., bool]] = None) -> ~T:
633    def last(self, predicate: Optional[Callable[..., bool]] = None) -> T:
634        """
635        Returns last element.
636
637        Example 1:
638        >>> lst = ['a', 'b', 'c']
639        >>> it(lst).last()
640        'c'
641
642        Example 2:
643        >>> lst = []
644        >>> it(lst).last()
645        Traceback (most recent call last):
646        ...
647        ValueError: Stream is empty.
648        """
649        v = self.last_or_none(predicate) if predicate is not None else self.last_or_none()
650        if v is None:
651            raise ValueError("Stream is empty.")
652        return v

Returns last element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last()
'c'

Example 2:

>>> lst = []
>>> it(lst).last()
Traceback (most recent call last):
...
ValueError: Stream is empty.
def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[~T]:
662    def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
663        """
664        Returns the last element matching the given [predicate], or `None` if no such element was found.
665
666        Exmaple 1:
667        >>> lst = ['a', 'b', 'c']
668        >>> it(lst).last_or_none()
669        'c'
670
671        Exmaple 2:
672        >>> lst = ['a', 'b', 'c']
673        >>> it(lst).last_or_none(lambda x: x != 'c')
674        'b'
675
676        Exmaple 3:
677        >>> lst = []
678        >>> it(lst).last_or_none(lambda x: x != 'c') is None
679        True
680        """
681        last: Optional[T] = None
682        for i in self if predicate is None else self.filter(predicate):
683            last = i
684        return last

Returns the last element matching the given [predicate], or None if no such element was found.

Exmaple 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_or_none()
'c'

Exmaple 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_or_none(lambda x: x != 'c')
'b'

Exmaple 3:

>>> lst = []
>>> it(lst).last_or_none(lambda x: x != 'c') is None
True
def index_of_or_none(self, element: ~T) -> Optional[int]:
686    def index_of_or_none(self, element: T) -> Optional[int]:
687        """
688        Returns first index of [element], or None if the collection does not contain element.
689
690        Example 1:
691        >>> lst = ['a', 'b', 'c']
692        >>> it(lst).index_of_or_none('b')
693        1
694
695        Example 2:
696        >>> lst = ['a', 'b', 'c']
697        >>> it(lst).index_of_or_none('d')
698        """
699        for i, x in enumerate(self):
700            if x == element:
701                return i
702        return None

Returns first index of [element], or None if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_none('b')
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_none('d')
def index_of(self, element: ~T) -> int:
704    def index_of(self, element: T) -> int:
705        """
706        Returns first index of [element], or -1 if the collection does not contain element.
707
708        Example 1:
709        >>> lst = ['a', 'b', 'c']
710        >>> it(lst).index_of('b')
711        1
712
713        Example 2:
714        >>> lst = ['a', 'b', 'c']
715        >>> it(lst).index_of('d')
716        -1
717        """
718        return none_or(self.index_of_or_none(element), -1)

Returns first index of [element], or -1 if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of('b')
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of('d')
-1
def index_of_or(self, element: ~T, default: int) -> int:
720    def index_of_or(self, element: T, default: int) -> int:
721        """
722        Returns first index of [element], or default value if the collection does not contain element.
723
724        Example 1:
725        >>> lst = ['a', 'b', 'c']
726        >>> it(lst).index_of_or('b', 1)
727        1
728
729        Example 2:
730        >>> lst = ['a', 'b', 'c']
731        >>> it(lst).index_of_or('d', 0)
732        0
733        """
734        return none_or(self.index_of_or_none(element), default)

Returns first index of [element], or default value if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or('b', 1)
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or('d', 0)
0
def index_of_or_else(self, element: ~T, f: Callable[[], int]) -> int:
736    def index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
737        """
738        Returns first index of [element], or computes the value from a callback if the collection does not contain element.
739
740        Example 1:
741        >>> lst = ['a', 'b', 'c']
742        >>> it(lst).index_of_or_else('b', lambda: 2)
743        1
744
745        Example 2:
746        >>> lst = ['a', 'b', 'c']
747        >>> it(lst).index_of_or_else('d', lambda: 0)
748        0
749        """
750        return none_or_else(self.index_of_or_none(element), f)

Returns first index of [element], or computes the value from a callback if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_else('b', lambda: 2)
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_else('d', lambda: 0)
0
def last_index_of_or_none(self, element: ~T) -> Optional[int]:
752    def last_index_of_or_none(self, element: T) -> Optional[int]:
753        """
754         Returns last index of [element], or None if the collection does not contain element.
755
756        Example 1:
757        >>> lst = ['a', 'b', 'c', 'b']
758        >>> it(lst).last_index_of_or_none('b')
759        3
760
761        Example 2:
762        >>> lst = ['a', 'b', 'c']
763        >>> it(lst).last_index_of_or_none('d')
764        """
765        seq = self.reversed()
766        last_idx = len(seq) - 1
767        for i, x in enumerate(seq):
768            if x == element:
769                return last_idx - i
770        return None

Returns last index of [element], or None if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or_none('b')
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or_none('d')
def last_index_of(self, element: ~T) -> int:
772    def last_index_of(self, element: T) -> int:
773        """
774         Returns last index of [element], or -1 if the collection does not contain element.
775
776        Example 1:
777        >>> lst = ['a', 'b', 'c', 'b']
778        >>> it(lst).last_index_of('b')
779        3
780
781        Example 2:
782        >>> lst = ['a', 'b', 'c']
783        >>> it(lst).last_index_of('d')
784        -1
785        """
786        return none_or(self.last_index_of_or_none(element), -1)

Returns last index of [element], or -1 if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of('b')
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of('d')
-1
def last_index_of_or(self, element: ~T, default: int) -> int:
788    def last_index_of_or(self, element: T, default: int) -> int:
789        """
790         Returns last index of [element], or default value if the collection does not contain element.
791
792        Example 1:
793        >>> lst = ['a', 'b', 'c', 'b']
794        >>> it(lst).last_index_of_or('b', 0)
795        3
796
797        Example 2:
798        >>> lst = ['a', 'b', 'c']
799        >>> it(lst).last_index_of_or('d', len(lst))
800        3
801        """
802        return none_or(self.last_index_of_or_none(element), default)

Returns last index of [element], or default value if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or('b', 0)
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or('d', len(lst))
3
def last_index_of_or_else(self, element: ~T, f: Callable[[], int]) -> int:
804    def last_index_of_or_else(self, element: T, f: Callable[[], int]) -> int:
805        """
806         Returns last index of [element], or computes the value from a callback if the collection does not contain element.
807
808        Example 1:
809        >>> lst = ['a', 'b', 'c', 'b']
810        >>> it(lst).last_index_of_or_else('b', lambda: 0)
811        3
812
813        Example 2:
814        >>> lst = ['a', 'b', 'c']
815        >>> it(lst).last_index_of_or_else('d', lambda: len(lst))
816        3
817        """
818        return none_or_else(self.last_index_of_or_none(element), f)

Returns last index of [element], or computes the value from a callback if the collection does not contain element.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or_else('b', lambda: 0)
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or_else('d', lambda: len(lst))
3
def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
828    def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
829        """
830        Returns first index of element matching the given [predicate], or None if no such element was found.
831
832        Example 1:
833        >>> lst = ['a', 'b', 'c']
834        >>> it(lst).index_of_first_or_none(lambda x: x == 'b')
835        1
836
837        Example 2:
838        >>> lst = ['a', 'b', 'c']
839        >>> it(lst).index_of_first_or_none(lambda x: x == 'd')
840        """
841        predicate = self.__callback_overload_warpper__(predicate)
842        for i, x in enumerate(self):
843            if predicate(x):
844                return i
845        return None

Returns first index of element matching the given [predicate], or None if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_none(lambda x: x == 'b')
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_none(lambda x: x == 'd')
def index_of_first(self, predicate: Callable[..., bool]) -> int:
853    def index_of_first(self, predicate: Callable[..., bool]) -> int:
854        """
855        Returns first index of element matching the given [predicate], or -1 if no such element was found.
856
857        Example 1:
858        >>> lst = ['a', 'b', 'c']
859        >>> it(lst).index_of_first(lambda x: x == 'b')
860        1
861
862        Example 2:
863        >>> lst = ['a', 'b', 'c']
864        >>> it(lst).index_of_first(lambda x: x == 'd')
865        -1
866
867        Example 3:
868        >>> lst = ['a', 'b', 'c']
869        >>> it(lst).index_of_first(lambda x: x == 'a')
870        0
871        """
872        return none_or(self.index_of_first_or_none(predicate), -1)

Returns first index of element matching the given [predicate], or -1 if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'b')
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'd')
-1

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'a')
0
def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int:
882    def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int:
883        """
884        Returns first index of element matching the given [predicate], or default value if no such element was found.
885
886        Example 1:
887        >>> lst = ['a', 'b', 'c']
888        >>> it(lst).index_of_first_or(lambda x: x == 'b', 0)
889        1
890
891        Example 2:
892        >>> lst = ['a', 'b', 'c']
893        >>> it(lst).index_of_first_or(lambda x: x == 'd', 0)
894        0
895
896        Example 3:
897        >>> lst = ['a', 'b', 'c']
898        >>> it(lst).index_of_first_or(lambda x: x == 'a', 0)
899        0
900        """
901        return none_or(self.index_of_first_or_none(predicate), default)

Returns first index of element matching the given [predicate], or default value if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'b', 0)
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'd', 0)
0

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'a', 0)
0
def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
915    def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
916        """
917        Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found.
918
919        Example 1:
920        >>> lst = ['a', 'b', 'c']
921        >>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst))
922        1
923
924        Example 2:
925        >>> lst = ['a', 'b', 'c']
926        >>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst))
927        3
928
929        Example 3:
930        >>> lst = ['a', 'b', 'c']
931        >>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst))
932        0
933        """
934        return none_or_else(self.index_of_first_or_none(predicate), f)

Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst))
1

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst))
3

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst))
0
def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
944    def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]:
945        """
946        Returns last index of element matching the given [predicate], or -1 if no such element was found.
947
948        Example 1:
949        >>> lst = ['a', 'b', 'c', 'b']
950        >>> it(lst).index_of_last_or_none(lambda x: x == 'b')
951        3
952
953        Example 2:
954        >>> lst = ['a', 'b', 'c']
955        >>> it(lst).index_of_last_or_none(lambda x: x == 'd')
956        """
957        seq = self.reversed()
958        last_idx = len(seq) - 1
959        predicate = self.__callback_overload_warpper__(predicate)
960        for i, x in enumerate(seq):
961            if predicate(x):
962                return last_idx - i
963        return None

Returns last index of element matching the given [predicate], or -1 if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or_none(lambda x: x == 'b')
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_none(lambda x: x == 'd')
def index_of_last(self, predicate: Callable[..., bool]) -> int:
971    def index_of_last(self, predicate: Callable[..., bool]) -> int:
972        """
973        Returns last index of element matching the given [predicate], or -1 if no such element was found.
974
975        Example 1:
976        >>> lst = ['a', 'b', 'c', 'b']
977        >>> it(lst).index_of_last(lambda x: x == 'b')
978        3
979
980        Example 2:
981        >>> lst = ['a', 'b', 'c']
982        >>> it(lst).index_of_last(lambda x: x == 'd')
983        -1
984
985        Example 3:
986        >>> lst = ['a', 'b', 'c']
987        >>> it(lst).index_of_last(lambda x: x == 'a')
988        0
989        """
990        return none_or(self.index_of_last_or_none(predicate), -1)

Returns last index of element matching the given [predicate], or -1 if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last(lambda x: x == 'b')
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last(lambda x: x == 'd')
-1

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last(lambda x: x == 'a')
0
def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int:
1000    def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int:
1001        """
1002        Returns last index of element matching the given [predicate], or default value if no such element was found.
1003
1004        Example 1:
1005        >>> lst = ['a', 'b', 'c', 'b']
1006        >>> it(lst).index_of_last_or(lambda x: x == 'b', 0)
1007        3
1008
1009        Example 2:
1010        >>> lst = ['a', 'b', 'c']
1011        >>> it(lst).index_of_last_or(lambda x: x == 'd', -99)
1012        -99
1013
1014        Example 3:
1015        >>> lst = ['a', 'b', 'c']
1016        >>> it(lst).index_of_last_or(lambda x: x == 'a', 0)
1017        0
1018        """
1019        return none_or(self.index_of_last_or_none(predicate), default)

Returns last index of element matching the given [predicate], or default value if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or(lambda x: x == 'b', 0)
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or(lambda x: x == 'd', -99)
-99

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or(lambda x: x == 'a', 0)
0
def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
1033    def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int:
1034        """
1035        Returns last index of element matching the given [predicate], or default value if no such element was found.
1036
1037        Example 1:
1038        >>> lst = ['a', 'b', 'c', 'b']
1039        >>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst))
1040        3
1041
1042        Example 2:
1043        >>> lst = ['a', 'b', 'c']
1044        >>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst))
1045        -3
1046
1047        Example 3:
1048        >>> lst = ['a', 'b', 'c']
1049        >>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst))
1050        0
1051        """
1052        return none_or_else(self.index_of_last_or_none(predicate), f)

Returns last index of element matching the given [predicate], or default value if no such element was found.

Example 1:

>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst))
3

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst))
-3

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst))
0
def single(self, predicate: Optional[Callable[..., bool]] = None) -> ~T:
1062    def single(self, predicate: Optional[Callable[..., bool]] = None) -> T:
1063        """
1064        Returns the single element matching the given [predicate], or throws exception if there is no
1065        or more than one matching element.
1066
1067        Exmaple 1:
1068        >>> lst = ['a']
1069        >>> it(lst).single()
1070        'a'
1071
1072        Exmaple 2:
1073        >>> lst = []
1074        >>> it(lst).single() is None
1075        Traceback (most recent call last):
1076        ...
1077        ValueError: Stream contains no element matching the predicate.
1078
1079        Exmaple 2:
1080        >>> lst = ['a', 'b']
1081        >>> it(lst).single() is None
1082        Traceback (most recent call last):
1083        ...
1084        ValueError: Stream contains more than one matching element.
1085        """
1086        single: Optional[T] = None
1087        found = False
1088        for i in self if predicate is None else self.filter(predicate):
1089            if found:
1090                raise ValueError("Stream contains more than one matching element.")
1091            single = i
1092            found = True
1093        if single is None:
1094            raise ValueError("Stream contains no element matching the predicate.")
1095        return single

Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.

Exmaple 1:

>>> lst = ['a']
>>> it(lst).single()
'a'

Exmaple 2:

>>> lst = []
>>> it(lst).single() is None
Traceback (most recent call last):
...
ValueError: Stream contains no element matching the predicate.

Exmaple 2:

>>> lst = ['a', 'b']
>>> it(lst).single() is None
Traceback (most recent call last):
...
ValueError: Stream contains more than one matching element.
def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[~T]:
1105    def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]:
1106        """
1107        Returns the single element matching the given [predicate], or `None` if element was not found
1108        or more than one element was found.
1109
1110        Exmaple 1:
1111        >>> lst = ['a']
1112        >>> it(lst).single_or_none()
1113        'a'
1114
1115        Exmaple 2:
1116        >>> lst = []
1117        >>> it(lst).single_or_none()
1118
1119        Exmaple 2:
1120        >>> lst = ['a', 'b']
1121        >>> it(lst).single_or_none()
1122
1123        """
1124        single: Optional[T] = None
1125        found = False
1126        for i in self if predicate is None else self.filter(predicate):
1127            if found:
1128                return None
1129            single = i
1130            found = True
1131        if not found:
1132            return None
1133        return single

Returns the single element matching the given [predicate], or None if element was not found or more than one element was found.

Exmaple 1:

>>> lst = ['a']
>>> it(lst).single_or_none()
'a'

Exmaple 2:

>>> lst = []
>>> it(lst).single_or_none()

Exmaple 2:

>>> lst = ['a', 'b']
>>> it(lst).single_or_none()
def drop(self, n: int) -> Stream[~T]:
1136    def drop(self, n: int) -> Stream[T]:
1137        """
1138        Returns a Stream containing all elements except first [n] elements.
1139
1140        Example 1:
1141        >>> lst = ['a', 'b', 'c']
1142        >>> it(lst).drop(0).to_list()
1143        ['a', 'b', 'c']
1144
1145        Example 2:
1146        >>> lst = ['a', 'b', 'c']
1147        >>> it(lst).drop(1).to_list()
1148        ['b', 'c']
1149
1150        Example 2:
1151        >>> lst = ['a', 'b', 'c']
1152        >>> it(lst).drop(4).to_list()
1153        []
1154        """
1155        if n < 0:
1156            raise ValueError(f"Requested element count {n} is less than zero.")
1157        if n == 0:
1158            return self
1159
1160        from .drop import DropTransform
1161
1162        return it(DropTransform(self, n))

Returns a Stream containing all elements except first [n] elements.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(0).to_list()
['a', 'b', 'c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(1).to_list()
['b', 'c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(4).to_list()
[]
def drop_while(self, predicate: Callable[..., bool]) -> Stream[~T]:
1171    def drop_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1172        """
1173        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1174
1175        Example 1:
1176        >>> lst = [1, 2, 3, 4, 1]
1177        >>> it(lst).drop_while(lambda x: x < 3 ).to_list()
1178        [3, 4, 1]
1179        """
1180        from .drop_while import DropWhileTransform
1181
1182        return it(DropWhileTransform(self, self.__callback_overload_warpper__(predicate)))

Returns a Stream containing all elements except first elements that satisfy the given [predicate].

Example 1:

>>> lst = [1, 2, 3, 4, 1]
>>> it(lst)pyiter.drop_while(lambda x: x < 3 ).to_list()
[3, 4, 1]
def drop_until(self, predicate: Callable[..., bool]) -> Stream[~T]:
1191    def drop_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1192        """
1193        Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate].
1194
1195        Example 1:
1196        >>> lst = [1, 2, 3, 4, 1]
1197        >>> it(lst).drop_until(lambda x: x >= 3).to_list()
1198        [3, 4, 1]
1199
1200        Example 2:
1201        >>> lst = [1, 2, 1, 4]
1202        >>> it(lst).drop_until(lambda x: x == 4).to_list()
1203        [4]
1204        """
1205        from .drop_until import DropUntilTransform
1206
1207        return it(DropUntilTransform(self, self.__callback_overload_warpper__(predicate)))

Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate].

Example 1:

>>> lst = [1, 2, 3, 4, 1]
>>> it(lst)pyiter.drop_until(lambda x: x >= 3).to_list()
[3, 4, 1]

Example 2:

>>> lst = [1, 2, 1, 4]
>>> it(lst)pyiter.drop_until(lambda x: x == 4).to_list()
[4]
def drop_last(self, n: int) -> Stream[~T]:
1209    def drop_last(self, n: int) -> Stream[T]:
1210        """
1211        Returns a Stream containing all elements except last [n] elements.
1212
1213        Example 1:
1214        >>> lst = ['a', 'b', 'c']
1215        >>> it(lst).drop_last(0).to_list()
1216        ['a', 'b', 'c']
1217
1218        Example 2:
1219        >>> lst = ['a', 'b', 'c']
1220        >>> it(lst).drop_last(1).to_list()
1221        ['a', 'b']
1222
1223        Example 3:
1224        >>> lst = ['a', 'b', 'c']
1225        >>> it(lst).drop_last(4).to_list()
1226        []
1227        """
1228        if n < 0:
1229            raise ValueError(f"Requested element count {n} is less than zero.")
1230        if n == 0:
1231            return self
1232
1233        size = len(self)
1234        if size <= n:
1235            return Stream([])
1236        return self.take(size - n)

Returns a Stream containing all elements except last [n] elements.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(0).to_list()
['a', 'b', 'c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(1).to_list()
['a', 'b']

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(4).to_list()
[]
def skip(self, n: int) -> Stream[~T]:
1238    def skip(self, n: int) -> Stream[T]:
1239        """
1240        Returns a Stream containing all elements except first [n] elements.
1241
1242        Example 1:
1243        >>> lst = ['a', 'b', 'c']
1244        >>> it(lst).skip(0).to_list()
1245        ['a', 'b', 'c']
1246
1247         Example 2:
1248        >>> lst = ['a', 'b', 'c']
1249        >>> it(lst).skip(1).to_list()
1250        ['b', 'c']
1251
1252        Example 2:
1253        >>> lst = ['a', 'b', 'c']
1254        >>> it(lst).skip(4).to_list()
1255        []
1256        """
1257        return self.drop(n)

Returns a Stream containing all elements except first [n] elements.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(0).to_list()
['a', 'b', 'c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(1).to_list()
['b', 'c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(4).to_list()
[]
def skip_while(self, predicate: Callable[..., bool]) -> Stream[~T]:
1265    def skip_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1266        """
1267        Returns a Stream containing all elements except first elements that satisfy the given [predicate].
1268
1269        Example 1:
1270        >>> lst = [1, 2, 3, 4, 1]
1271        >>> it(lst).skip_while(lambda x: x < 3 ).to_list()
1272        [3, 4, 1]
1273        """
1274        return self.drop_while(predicate)

Returns a Stream containing all elements except first elements that satisfy the given [predicate].

Example 1:

>>> lst = [1, 2, 3, 4, 1]
>>> it(lst).skip_while(lambda x: x < 3 ).to_list()
[3, 4, 1]
def take(self, n: int) -> Stream[~T]:
1276    def take(self, n: int) -> Stream[T]:
1277        """
1278        Returns an Stream containing first [n] elements.
1279
1280        Example 1:
1281        >>> a = ['a', 'b', 'c']
1282        >>> it(a).take(0).to_list()
1283        []
1284
1285        Example 2:
1286        >>> a = ['a', 'b', 'c']
1287        >>> it(a).take(2).to_list()
1288        ['a', 'b']
1289        """
1290        if n < 0:
1291            raise ValueError(f"Requested element count {n} is less than zero.")
1292        if n == 0:
1293            return Stream([])
1294        from .take import TakeTransform
1295
1296        return it(TakeTransform(self, n))

Returns an Stream containing first [n] elements.

Example 1:

>>> a = ['a', 'b', 'c']
>>> it(a)pyiter.take(0).to_list()
[]

Example 2:

>>> a = ['a', 'b', 'c']
>>> it(a)pyiter.take(2).to_list()
['a', 'b']
def take_while(self, predicate: Callable[..., bool]) -> Stream[~T]:
1305    def take_while(self, predicate: Callable[..., bool]) -> Stream[T]:
1306        """
1307        Returns an Stream containing first elements satisfying the given [predicate].
1308
1309        Example 1:
1310        >>> lst = ['a', 'b', 'c', 'd']
1311        >>> it(lst).take_while(lambda x: x in ['a', 'b']).to_list()
1312        ['a', 'b']
1313        """
1314        from .take_while import TakeWhileTransform
1315
1316        return it(TakeWhileTransform(self, self.__callback_overload_warpper__(predicate)))

Returns an Stream containing first elements satisfying the given [predicate].

Example 1:

>>> lst = ['a', 'b', 'c', 'd']
>>> it(lst)pyiter.take_while(lambda x: x in ['a', 'b']).to_list()
['a', 'b']
def take_until(self, predicate: Callable[..., bool]) -> Stream[~T]:
1325    def take_until(self, predicate: Callable[..., bool]) -> Stream[T]:
1326        """
1327        Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate].
1328
1329        Example 1:
1330        >>> lst = [1, 2, 3, 4]
1331        >>> it(lst).take_until(lambda x: x > 2).to_list()
1332        [1, 2]
1333
1334        Example 2:
1335        >>> lst = [1, 2, 3, 4]
1336        >>> it(lst).take_until(lambda x: x > 10).to_list()
1337        [1, 2, 3, 4]
1338        """
1339        from .take_until import TakeUntilTransform
1340
1341        return it(TakeUntilTransform(self, self.__callback_overload_warpper__(predicate)))

Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate].

Example 1:

>>> lst = [1, 2, 3, 4]
>>> it(lst)pyiter.take_until(lambda x: x > 2).to_list()
[1, 2]

Example 2:

>>> lst = [1, 2, 3, 4]
>>> it(lst)pyiter.take_until(lambda x: x > 10).to_list()
[1, 2, 3, 4]
def take_last(self, n: int) -> Stream[~T]:
1343    def take_last(self, n: int) -> Stream[T]:
1344        """
1345        Returns an Stream containing last [n] elements.
1346
1347        Example 1:
1348        >>> a = ['a', 'b', 'c']
1349        >>> it(a).take_last(0).to_list()
1350        []
1351
1352        Example 2:
1353        >>> a = ['a', 'b', 'c']
1354        >>> it(a).take_last(2).to_list()
1355        ['b', 'c']
1356
1357        Example 3:
1358        >>> a = ['a', 'b', 'c']
1359        >>> it(a).take_last(10).to_list()
1360        ['a', 'b', 'c']
1361        """
1362        if n < 0:
1363            raise ValueError(f"Requested element count {n} is less than zero.")
1364        if n == 0:
1365            return Stream([])
1366
1367        return self.drop(max(len(self) - n, 0))

Returns an Stream containing last [n] elements.

Example 1:

>>> a = ['a', 'b', 'c']
>>> it(a).take_last(0).to_list()
[]

Example 2:

>>> a = ['a', 'b', 'c']
>>> it(a).take_last(2).to_list()
['b', 'c']

Example 3:

>>> a = ['a', 'b', 'c']
>>> it(a).take_last(10).to_list()
['a', 'b', 'c']
def sorted(self) -> Stream[~T]:
1370    def sorted(self) -> Stream[T]:
1371        """
1372        Returns an Stream that yields elements of this Stream sorted according to their natural sort order.
1373
1374        Example 1:
1375        >>> lst = ['b', 'a', 'e', 'c']
1376        >>> it(lst).sorted().to_list()
1377        ['a', 'b', 'c', 'e']
1378
1379         Example 2:
1380        >>> lst = [2, 1, 4, 3]
1381        >>> it(lst).sorted().to_list()
1382        [1, 2, 3, 4]
1383        """
1384        lst = list(self)
1385        lst.sort()  # type: ignore
1386        return it(lst)

Returns an Stream that yields elements of this Stream sorted according to their natural sort order.

Example 1:

>>> lst = ['b', 'a', 'e', 'c']
>>> it(lst).sorted().to_list()
['a', 'b', 'c', 'e']

Example 2:

>>> lst = [2, 1, 4, 3]
>>> it(lst).sorted().to_list()
[1, 2, 3, 4]
def sorted_by( self, key_selector: 'Callable[..., SupportsRichComparisonT]') -> Stream[~T]:
1397    def sorted_by(self, key_selector: Callable[..., SupportsRichComparisonT]) -> Stream[T]:
1398        """
1399        Returns a sequence that yields elements of this sequence sorted according to natural sort
1400        order of the value returned by specified [key_selector] function.
1401
1402        Example 1:
1403        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1404        >>> it(lst).sorted_by(lambda x: x['name']).to_list()
1405        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1406        >>> it(lst).sorted_by(lambda x: x['age']).to_list()
1407        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1408        """
1409        lst = list(self)
1410        lst.sort(key=self.__callback_overload_warpper__(key_selector))
1411        return it(lst)

Returns a sequence that yields elements of this sequence sorted according to natural sort order of the value returned by specified [key_selector] function.

Example 1:

>>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
>>> it(lst).sorted_by(lambda x: x['name']).to_list()
[{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
>>> it(lst).sorted_by(lambda x: x['age']).to_list()
[{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
def sorted_descending(self) -> Stream[~T]:
1413    def sorted_descending(self) -> Stream[T]:
1414        """
1415        Returns a Stream of all elements sorted descending according to their natural sort order.
1416
1417        Example 1:
1418        >>> lst = ['b', 'c', 'a']
1419        >>> it(lst).sorted_descending().to_list()
1420        ['c', 'b', 'a']
1421        """
1422        return self.sorted().reversed()

Returns a Stream of all elements sorted descending according to their natural sort order.

Example 1:

>>> lst = ['b', 'c', 'a']
>>> it(lst).sorted_descending().to_list()
['c', 'b', 'a']
def sorted_by_descending( self, key_selector: 'Callable[..., SupportsRichComparisonT]') -> Stream[~T]:
1436    def sorted_by_descending(
1437        self, key_selector: Callable[..., SupportsRichComparisonT]
1438    ) -> Stream[T]:
1439        """
1440        Returns a sequence that yields elements of this sequence sorted descending according
1441        to natural sort order of the value returned by specified [key_selector] function.
1442
1443        Example 1:
1444        >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
1445        >>> it(lst).sorted_by_descending(lambda x: x['name']).to_list()
1446        [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1447        >>> it(lst).sorted_by_descending(lambda x: x['age']).to_list()
1448        [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1449        """
1450        return self.sorted_by(key_selector).reversed()

Returns a sequence that yields elements of this sequence sorted descending according to natural sort order of the value returned by specified [key_selector] function.

Example 1:

>>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
>>> it(lst).sorted_by_descending(lambda x: x['name']).to_list()
[{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
>>> it(lst).sorted_by_descending(lambda x: x['age']).to_list()
[{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
def sorted_with(self, comparator: Callable[[~T, ~T], int]) -> Stream[~T]:
1453    def sorted_with(self, comparator: Callable[[T, T], int]) -> Stream[T]:
1454        """
1455        Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
1456
1457        Example 1:
1458        >>> lst = ['aa', 'bbb', 'c']
1459        >>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list()
1460        ['c', 'aa', 'bbb']
1461        """
1462        from functools import cmp_to_key
1463
1464        lst = list(self)
1465        lst.sort(key=cmp_to_key(comparator))
1466        return it(lst)

Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].

Example 1:

>>> lst = ['aa', 'bbb', 'c']
>>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list()
['c', 'aa', 'bbb']
def associate(self, transform: Callable[..., Tuple[~K, ~O]]) -> Dict[~K, ~O]:
1474    def associate(self, transform: Callable[..., Tuple[K, V]]) -> Dict[K, V]:
1475        """
1476        Returns a [Dict] containing key-value Tuple provided by [transform] function
1477        applied to elements of the given Stream.
1478
1479        Example 1:
1480        >>> lst = ['1', '2', '3']
1481        >>> it(lst).associate(lambda x: (int(x), x))
1482        {1: '1', 2: '2', 3: '3'}
1483        """
1484        transform = self.__callback_overload_warpper__(transform)
1485        dic: Dict[K, V] = dict()
1486        for i in self:
1487            k, v = transform(i)
1488            dic[k] = v
1489        return dic

Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.

Example 1:

>>> lst = ['1', '2', '3']
>>> it(lst).associate(lambda x: (int(x), x))
{1: '1', 2: '2', 3: '3'}
def associate_by( self, key_selector: Callable[..., ~K], value_transform: Optional[Callable[[~T], ~O]] = None) -> Union[Dict[~K, ~T], Dict[~K, ~O]]:
1501    def associate_by(
1502        self,
1503        key_selector: Callable[..., K],
1504        value_transform: Optional[Callable[[T], V]] = None,
1505    ) -> Union[Dict[K, T], Dict[K, V]]:
1506        """
1507        Returns a [Dict] containing key-value Tuple provided by [transform] function
1508        applied to elements of the given Stream.
1509
1510        Example 1:
1511        >>> lst = ['1', '2', '3']
1512        >>> it(lst).associate_by(lambda x: int(x))
1513        {1: '1', 2: '2', 3: '3'}
1514
1515        Example 2:
1516        >>> lst = ['1', '2', '3']
1517        >>> it(lst).associate_by(lambda x: int(x), lambda x: x+x)
1518        {1: '11', 2: '22', 3: '33'}
1519
1520        """
1521        key_selector = self.__callback_overload_warpper__(key_selector)
1522
1523        dic: Dict[K, Any] = dict()
1524        for i in self:
1525            k = key_selector(i)
1526            dic[k] = i if value_transform is None else value_transform(i)
1527        return dic

Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.

Example 1:

>>> lst = ['1', '2', '3']
>>> it(lst).associate_by(lambda x: int(x))
{1: '1', 2: '2', 3: '3'}

Example 2:

>>> lst = ['1', '2', '3']
>>> it(lst).associate_by(lambda x: int(x), lambda x: x+x)
{1: '11', 2: '22', 3: '33'}
def associate_by_to( self, destination: Dict[~K, Any], key_selector: Callable[[~T], ~K], value_transform: Optional[Callable[[~T], Any]] = None) -> Dict[~K, Any]:
1540    def associate_by_to(
1541        self,
1542        destination: Dict[K, Any],
1543        key_selector: Callable[[T], K],
1544        value_transform: Optional[Callable[[T], Any]] = None,
1545    ) -> Dict[K, Any]:
1546        """
1547        Returns a [Dict] containing key-value Tuple provided by [transform] function
1548        applied to elements of the given Stream.
1549
1550        Example 1:
1551        >>> lst = ['1', '2', '3']
1552        >>> it(lst).associate_by_to({}, lambda x: int(x))
1553        {1: '1', 2: '2', 3: '3'}
1554
1555        Example 2:
1556        >>> lst = ['1', '2', '3']
1557        >>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' )
1558        {1: '1!', 2: '2!', 3: '3!'}
1559
1560        """
1561        for i in self:
1562            k = key_selector(i)
1563            destination[k] = i if value_transform is None else value_transform(i)
1564        return destination

Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.

Example 1:

>>> lst = ['1', '2', '3']
>>> it(lst).associate_by_to({}, lambda x: int(x))
{1: '1', 2: '2', 3: '3'}

Example 2:

>>> lst = ['1', '2', '3']
>>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' )
{1: '1!', 2: '2!', 3: '3!'}
def all(self, predicate: Callable[..., bool]) -> bool:
1572    def all(self, predicate: Callable[..., bool]) -> bool:
1573        """
1574        Returns True if all elements of the Stream satisfy the specified [predicate] function.
1575
1576        Example 1:
1577        >>> lst = [1, 2, 3]
1578        >>> it(lst).all(lambda x: x > 0)
1579        True
1580        >>> it(lst).all(lambda x: x > 1)
1581        False
1582        """
1583        predicate = self.__callback_overload_warpper__(predicate)
1584        for i in self:
1585            if not predicate(i):
1586                return False
1587        return True

Returns True if all elements of the Stream satisfy the specified [predicate] function.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).all(lambda x: x > 0)
True
>>> it(lst).all(lambda x: x > 1)
False
def any(self, predicate: Callable[..., bool]) -> bool:
1595    def any(self, predicate: Callable[..., bool]) -> bool:
1596        """
1597        Returns True if any elements of the Stream satisfy the specified [predicate] function.
1598
1599        Example 1:
1600        >>> lst = [1, 2, 3]
1601        >>> it(lst).any(lambda x: x > 0)
1602        True
1603        >>> it(lst).any(lambda x: x > 3)
1604        False
1605        """
1606        predicate = self.__callback_overload_warpper__(predicate)
1607        for i in self:
1608            if predicate(i):
1609                return True
1610        return False

Returns True if any elements of the Stream satisfy the specified [predicate] function.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).any(lambda x: x > 0)
True
>>> it(lst).any(lambda x: x > 3)
False
def count(self, predicate: Optional[Callable[..., bool]] = None) -> int:
1620    def count(self, predicate: Optional[Callable[..., bool]] = None) -> int:
1621        """
1622        Returns the number of elements in the Stream that satisfy the specified [predicate] function.
1623
1624        Example 1:
1625        >>> lst = [1, 2, 3]
1626        >>> it(lst).count()
1627        3
1628        >>> it(lst).count(lambda x: x > 0)
1629        3
1630        >>> it(lst).count(lambda x: x > 2)
1631        1
1632        """
1633        if predicate is None:
1634            return len(self)
1635        predicate = self.__callback_overload_warpper__(predicate)
1636        return sum(1 for i in self if predicate(i))

Returns the number of elements in the Stream that satisfy the specified [predicate] function.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).count()
3
>>> it(lst).count(lambda x: x > 0)
3
>>> it(lst).count(lambda x: x > 2)
1
def contains(self, value: ~T) -> bool:
1638    def contains(self, value: T) -> bool:
1639        """
1640        Returns True if the Stream contains the specified [value].
1641
1642        Example 1:
1643        >>> lst = [1, 2, 3]
1644        >>> it(lst).contains(1)
1645        True
1646        >>> it(lst).contains(4)
1647        False
1648        """
1649        return value in self

Returns True if the Stream contains the specified [value].

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).contains(1)
True
>>> it(lst).contains(4)
False
def element_at(self, index: int) -> ~T:
1651    def element_at(self, index: int) -> T:
1652        """
1653        Returns the element at the specified [index] in the Stream.
1654
1655        Example 1:
1656        >>> lst = [1, 2, 3]
1657        >>> it(lst).element_at(1)
1658        2
1659
1660        Example 2:
1661        >>> lst = [1, 2, 3]
1662        >>> it(lst).element_at(3)
1663        Traceback (most recent call last):
1664        ...
1665        IndexError: Index 3 out of range
1666        """
1667        return self.element_at_or_else(
1668            index, lambda index: throw(IndexError(f"Index {index} out of range"))
1669        )

Returns the element at the specified [index] in the Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).element_at(1)
2

Example 2:

>>> lst = [1, 2, 3]
>>> it(lst).element_at(3)
Traceback (most recent call last):
...
IndexError: Index 3 out of range
def element_at_or_else( self, index: int, default: Union[Callable[[int], ~T], ~T, NoneType] = None) -> Optional[~T]:
1689    def element_at_or_else(
1690        self, index: int, default: Union[Callable[[int], T], T, None] = None
1691    ) -> Optional[T]:
1692        """
1693        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1694
1695        Example 1:
1696        >>> lst = [1, 2, 3]
1697        >>> it(lst).element_at_or_else(1, lambda x: 'default')
1698        2
1699        >>> it(lst).element_at_or_else(4, lambda x: 'default')
1700        'default'
1701
1702        """
1703        if index >= 0:
1704            if (
1705                isinstance(self.__transform__, NonTransform)
1706                and isinstance(self.__transform__.iter, list)
1707                and index < len(self.__transform__.iter)
1708            ):
1709                return self.__transform__.iter[index]
1710            for i, e in enumerate(self):
1711                if i == index:
1712                    return e
1713        return default(index) if callable(default) else default  # type: ignore

Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_else(1, lambda x: 'default')
2
>>> it(lst).element_at_or_else(4, lambda x: 'default')
'default'
def element_at_or_default(self, index: int, default: ~T) -> ~T:
1715    def element_at_or_default(self, index: int, default: T) -> T:
1716        """
1717        Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
1718
1719        Example 1:
1720        >>> lst = [1, 2, 3]
1721        >>> it(lst).element_at_or_default(1, 'default')
1722        2
1723        >>> it(lst).element_at_or_default(4, 'default')
1724        'default'
1725
1726        """
1727        return self.element_at_or_else(index, default)

Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_default(1, 'default')
2
>>> it(lst).element_at_or_default(4, 'default')
'default'
def element_at_or_none(self, index: int) -> Optional[~T]:
1729    def element_at_or_none(self, index: int) -> Optional[T]:
1730        """
1731        Returns the element at the specified [index] in the Stream or None if the index is out of bounds.
1732
1733        Example 1:
1734        >>> lst = [1, 2, 3]
1735        >>> it(lst).element_at_or_none(1)
1736        2
1737        >>> it(lst).element_at_or_none(4) is None
1738        True
1739        """
1740        return self.element_at_or_else(index)

Returns the element at the specified [index] in the Stream or None if the index is out of bounds.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_none(1)
2
>>> it(lst).element_at_or_none(4) is None
True
def distinct(self) -> Stream[~T]:
1742    def distinct(self) -> Stream[T]:
1743        """
1744        Returns a new Stream containing the distinct elements of the given Stream.
1745
1746        Example 1:
1747        >>> lst = [1, 2, 3, 1, 2, 3]
1748        >>> it(lst).distinct().to_list()
1749        [1, 2, 3]
1750
1751        Example 2:
1752        >>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1753        >>> it(lst).distinct().sorted().to_list()
1754        [(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1755
1756        """
1757        from .distinct import DistinctTransform
1758
1759        return it(DistinctTransform(self))

Returns a new Stream containing the distinct elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3, 1, 2, 3]
>>> it(lst)pyiter.distinct().to_list()
[1, 2, 3]

Example 2:

>>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
>>> it(lst)pyiter.distinct().sorted().to_list()
[(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[~T]:
1767    def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[T]:
1768        """
1769        Returns a new Stream containing the distinct elements of the given Stream.
1770
1771        Example 1:
1772        >>> lst = [1, 2, 3, 1, 2, 3]
1773        >>> it(lst).distinct_by(lambda x: x%2).to_list()
1774        [1, 2]
1775        """
1776        from .distinct import DistinctTransform
1777
1778        return it(DistinctTransform(self, self.__callback_overload_warpper__(key_selector)))

Returns a new Stream containing the distinct elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3, 1, 2, 3]
>>> it(lst).distinct_by(lambda x: x%2).to_list()
[1, 2]
def reduce( self, accumulator: Callable[..., ~U], initial: Optional[~U] = None) -> Optional[~U]:
1784    def reduce(self, accumulator: Callable[..., U], initial: Optional[U] = None) -> Optional[U]:
1785        """
1786        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1787
1788        Example 1:
1789        >>> lst = [1, 2, 3]
1790        >>> it(lst).reduce(lambda x, y: x+y)
1791        6
1792        """
1793        result: Optional[U] = initial
1794        for i, e in enumerate(self):
1795            if i == 0 and initial is None:
1796                result = e  # type: ignore
1797                continue
1798
1799            result = accumulator(result, e)
1800        return result

Returns the result of applying the specified [accumulator] function to the given Stream's elements.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).reduce(lambda x, y: x+y)
6
def fold(self, initial: ~U, accumulator: Callable[[~U, ~T], ~U]) -> ~U:
1802    def fold(self, initial: U, accumulator: Callable[[U, T], U]) -> U:
1803        """
1804        Returns the result of applying the specified [accumulator] function to the given Stream's elements.
1805
1806        Example 1:
1807        >>> lst = [1, 2, 3]
1808        >>> it(lst).fold(0, lambda x, y: x+y)
1809        6
1810        """
1811        return self.reduce(accumulator, initial)

Returns the result of applying the specified [accumulator] function to the given Stream's elements.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).fold(0, lambda x, y: x+y)
6
def sum_of(self, selector: Callable[[~T], Union[int, float]]) -> Union[int, float]:
1817    def sum_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1818        """
1819        Returns the sum of the elements of the given Stream.
1820
1821        Example 1:
1822        >>> lst = [1, 2, 3]
1823        >>> it(lst).sum_of(lambda x: x)
1824        6
1825        """
1826        return sum(selector(i) for i in self)

Returns the sum of the elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).sum_of(lambda x: x)
6
def max_of(self, selector: Callable[[~T], Union[int, float]]) -> Union[int, float]:
1832    def max_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1833        """
1834        Returns the maximum element of the given Stream.
1835
1836        Example 1:
1837        >>> lst = [1, 2, 3]
1838        >>> it(lst).max_of(lambda x: x)
1839        3
1840        """
1841        return max(selector(i) for i in self)

Returns the maximum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).max_of(lambda x: x)
3
def max_by_or_none(self, selector: Callable[[~T], Union[int, float]]) -> Optional[~T]:
1847    def max_by_or_none(self, selector: Callable[[T], Union[float, int]]) -> Optional[T]:
1848        """
1849        Returns the first element yielding the largest value of the given function
1850        or `none` if there are no elements.
1851
1852        Example 1:
1853        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1854        >>> it(lst).max_by_or_none(lambda x: x["num"])
1855        {'name': 'B', 'num': 200}
1856
1857        Example 2:
1858        >>> lst = []
1859        >>> it(lst).max_by_or_none(lambda x: x["num"])
1860        """
1861
1862        max_item = None
1863        max_val = None
1864
1865        for item in self:
1866            val = selector(item)
1867            if max_val is None or val > max_val:
1868                max_item = item
1869                max_val = val
1870
1871        return max_item

Returns the first element yielding the largest value of the given function or none if there are no elements.

Example 1:

>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).max_by_or_none(lambda x: x["num"])
{'name': 'B', 'num': 200}

Example 2:

>>> lst = []
>>> it(lst).max_by_or_none(lambda x: x["num"])
def max_by(self, selector: Callable[[~T], Union[int, float]]) -> ~T:
1877    def max_by(self, selector: Callable[[T], Union[float, int]]) -> T:
1878        """
1879        Returns the first element yielding the largest value of the given function.
1880
1881        Example 1:
1882        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1883        >>> it(lst).max_by(lambda x: x["num"])
1884        {'name': 'B', 'num': 200}
1885
1886        Exmaple 2:
1887        >>> lst = []
1888        >>> it(lst).max_by(lambda x: x["num"])
1889        Traceback (most recent call last):
1890        ...
1891        ValueError: Stream is empty.
1892        """
1893        max_item = self.max_by_or_none(selector)
1894        if max_item is None:
1895            raise ValueError("Stream is empty.")
1896        return max_item

Returns the first element yielding the largest value of the given function.

Example 1:

>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).max_by(lambda x: x["num"])
{'name': 'B', 'num': 200}

Exmaple 2:

>>> lst = []
>>> it(lst).max_by(lambda x: x["num"])
Traceback (most recent call last):
...
ValueError: Stream is empty.
def min_of(self, selector: Callable[[~T], Union[int, float]]) -> Union[int, float]:
1912    def min_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1913        return min(selector(i) for i in self)

Returns the minimum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).min_of(lambda x: x)
1
def min_by_or_none(self, selector: Callable[[~T], float]) -> Optional[~T]:
1919    def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]:
1920        """
1921        Returns the first element yielding the smallest value of the given function
1922        or `none` if there are no elements.
1923
1924        Example 1:
1925        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1926        >>> it(lst).min_by_or_none(lambda x: x["num"])
1927        {'name': 'A', 'num': 100}
1928
1929        Exmaple 2:
1930        >>> lst = []
1931        >>> it(lst).min_by_or_none(lambda x: x["num"])
1932        """
1933        min_item = None
1934        min_val = None
1935
1936        for item in self:
1937            val = selector(item)
1938            if min_val is None or val < min_val:
1939                min_item = item
1940                min_val = val
1941
1942        return min_item

Returns the first element yielding the smallest value of the given function or none if there are no elements.

Example 1:

>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).min_by_or_none(lambda x: x["num"])
{'name': 'A', 'num': 100}

Exmaple 2:

>>> lst = []
>>> it(lst).min_by_or_none(lambda x: x["num"])
def min_by(self, selector: Callable[[~T], float]) -> ~T:
1948    def min_by(self, selector: Callable[[T], float]) -> T:
1949        """
1950        Returns the first element yielding the smallest value of the given function.
1951
1952        Example 1:
1953        >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
1954        >>> it(lst).min_by(lambda x: x["num"])
1955        {'name': 'A', 'num': 100}
1956
1957        Exmaple 2:
1958        >>> lst = []
1959        >>> it(lst).min_by(lambda x: x["num"])
1960        Traceback (most recent call last):
1961        ...
1962        ValueError: Stream is empty.
1963        """
1964        min_item = self.min_by_or_none(selector)
1965        if min_item is None:
1966            raise ValueError("Stream is empty.")
1967
1968        return min_item

Returns the first element yielding the smallest value of the given function.

Example 1:

>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).min_by(lambda x: x["num"])
{'name': 'A', 'num': 100}

Exmaple 2:

>>> lst = []
>>> it(lst).min_by(lambda x: x["num"])
Traceback (most recent call last):
...
ValueError: Stream is empty.
def mean_of(self, selector: Callable[[~T], Union[int, float]]) -> Union[int, float]:
1970    def mean_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]:
1971        """
1972        Returns the mean of the elements of the given Stream.
1973
1974        Example 1:
1975        >>> lst = [1, 2, 3]
1976        >>> it(lst).mean_of(lambda x: x)
1977        2.0
1978        """
1979        return self.sum_of(selector) / len(self)

Returns the mean of the elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).mean_of(lambda x: x)
2.0
def sum( self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
1995    def sum(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
1996        """
1997        Returns the sum of the elements of the given Stream.
1998
1999        Example 1:
2000        >>> lst = [1, 2, 3]
2001        >>> it(lst).sum()
2002        6
2003        """
2004        return sum(self)

Returns the sum of the elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).sum()
6
def max( self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2010    def max(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2011        """
2012        Returns the maximum element of the given Stream.
2013
2014        Example 1:
2015        >>> lst = [1, 2, 3]
2016        >>> it(lst).max()
2017        3
2018        """
2019        return max(self)

Returns the maximum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).max()
3
def max_or_default( self: Union[Stream[int], Stream[float]], default: Optional[~O] = None) -> Union[float, int, ~O, NoneType]:
2029    def max_or_default(
2030        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2031    ) -> Union[float, int, V, None]:
2032        """
2033        Returns the maximum element of the given Stream.
2034
2035        Example 1:
2036        >>> lst = [1, 2, 3]
2037        >>> it(lst).max_or_default()
2038        3
2039
2040        Example 2:
2041        >>> lst = []
2042        >>> it(lst).max_or_default() is None
2043        True
2044
2045        Example 3:
2046        >>> lst = []
2047        >>> it(lst).max_or_default(9)
2048        9
2049        """
2050        if self.is_empty():
2051            return default
2052        return max(self)

Returns the maximum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).max_or_default()
3

Example 2:

>>> lst = []
>>> it(lst).max_or_default() is None
True

Example 3:

>>> lst = []
>>> it(lst).max_or_default(9)
9
def max_or_none( self: Union[Stream[int], Stream[float]]) -> Union[float, int, NoneType]:
2058    def max_or_none(
2059        self: Union[Stream[int], Stream[float]],
2060    ) -> Union[float, int, None]:
2061        """
2062        Returns the maximum element of the given Stream.
2063
2064        Example 1:
2065        >>> lst = [1, 2, 3]
2066        >>> it(lst).max_or_none()
2067        3
2068
2069        Example 2:
2070        >>> lst = []
2071        >>> it(lst).max_or_none() is None
2072        True
2073        """
2074        return self.max_or_default(None)

Returns the maximum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).max_or_none()
3

Example 2:

>>> lst = []
>>> it(lst).max_or_none() is None
True
def min( self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2090    def min(self: Union[Stream[int], Stream[float]]) -> Union[float, int]:
2091        """
2092        Returns the minimum element of the given Stream.
2093
2094        Example 1:
2095        >>> lst = [1, 2, 3]
2096        >>> it(lst).min()
2097        1
2098        """
2099        return min(self)

Returns the minimum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).min()
1
def min_or_none( self: Union[Stream[int], Stream[float]]) -> Union[float, int, NoneType]:
2115    def min_or_none(
2116        self: Union[Stream[int], Stream[float]],
2117    ) -> Union[float, int, None]:
2118        """
2119        Returns the minimum element of the given Stream.
2120
2121        Example 1:
2122        >>> lst = [1, 2, 3]
2123        >>> it(lst).min_or_none()
2124        1
2125        """
2126        return self.min_or_default(None)

Returns the minimum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).min_or_none()
1
def min_or_default( self: Union[Stream[int], Stream[float]], default: Optional[~O] = None) -> Union[float, int, ~O, NoneType]:
2146    def min_or_default(
2147        self: Union[Stream[int], Stream[float]], default: Optional[V] = None
2148    ) -> Union[float, int, V, None]:
2149        """
2150        Returns the minimum element of the given Stream.
2151
2152        Example 1:
2153        >>> lst = [1, 2, 3]
2154        >>> it(lst).min_or_default()
2155        1
2156
2157        Example 2:
2158        >>> lst = []
2159        >>> it(lst).min_or_default(9)
2160        9
2161        """
2162        if self.is_empty():
2163            return default
2164        return min(self)

Returns the minimum element of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).min_or_default()
1

Example 2:

>>> lst = []
>>> it(lst).min_or_default(9)
9
def mean( self: Union[Stream[int], Stream[float]]) -> float:
2180    def mean(self: Union[Stream[int], Stream[float]]) -> float:
2181        """
2182        Returns the mean of the elements of the given Stream.
2183
2184        Example 1:
2185        >>> lst = [1, 2, 3]
2186        >>> it(lst).mean()
2187        2.0
2188        """
2189        return self.sum() / len(self)

Returns the mean of the elements of the given Stream.

Example 1:

>>> lst = [1, 2, 3]
>>> it(lst).mean()
2.0
def reversed(self) -> Stream[~T]:
2192    def reversed(self) -> Stream[T]:
2193        """
2194        Returns a list with elements in reversed order.
2195
2196        Example 1:
2197        >>> lst = ['b', 'c', 'a']
2198        >>> it(lst).reversed().to_list()
2199        ['a', 'c', 'b']
2200        """
2201        lst = list(self)
2202        lst.reverse()
2203        return it(lst)

Returns a list with elements in reversed order.

Example 1:

>>> lst = ['b', 'c', 'a']
>>> it(lst).reversed().to_list()
['a', 'c', 'b']
def flat_map(self, transform: Callable[..., Iterable[~U]]) -> Stream[~U]:
2211    def flat_map(self, transform: Callable[..., Iterable[U]]) -> Stream[U]:
2212        """
2213        Returns a single list of all elements yielded from results of [transform]
2214        function being invoked on each element of original collection.
2215
2216        Example 1:
2217        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2218        >>> it(lst).flat_map(lambda x: x).to_list()
2219        ['a', 'b', 'c', 'd', 'e']
2220        """
2221        return self.map(transform).flatten()

Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.

Example 1:

>>> lst = [['a', 'b'], ['c'], ['d', 'e']]
>>> it(lst).flat_map(lambda x: x).to_list()
['a', 'b', 'c', 'd', 'e']
def flatten(self: Iterable[Iterable[~U]]) -> Stream[~U]:
2223    def flatten(self: Iterable[Iterable[U]]) -> Stream[U]:
2224        """
2225        Returns a sequence of all elements from all sequences in this sequence.
2226
2227        Example 1:
2228        >>> lst = [['a', 'b'], ['c'], ['d', 'e']]
2229        >>> it(lst).flatten().to_list()
2230        ['a', 'b', 'c', 'd', 'e']
2231        """
2232        from .flattening import FlatteningTransform
2233
2234        return it(FlatteningTransform(self))

Returns a sequence of all elements from all sequences in this sequence.

Example 1:

>>> lst = [['a', 'b'], ['c'], ['d', 'e']]
>>> it(lst).flatten().to_list()
['a', 'b', 'c', 'd', 'e']
def group_by(self, key_selector: Callable[..., ~K]) -> 'Stream[Grouping[K, T]]':
2244    def group_by(self, key_selector: Callable[..., K]) -> Stream[Grouping[K, T]]:
2245        """
2246        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2247        and values being the corresponding elements of original collection.
2248
2249        Example 1:
2250        >>> lst = [1, 2, 3, 4, 5]
2251        >>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list()
2252        [(1, [1, 3, 5]), (0, [2, 4])]
2253        """
2254        from .grouping import GroupingTransform
2255
2256        return it(GroupingTransform(self, self.__callback_overload_warpper__(key_selector)))

Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection and values being the corresponding elements of original collection.

Example 1:

>>> lst = [1, 2, 3, 4, 5]
>>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list()
[(1, [1, 3, 5]), (0, [2, 4])]
def group_by_to( self, destination: Dict[~K, List[~T]], key_selector: Callable[..., ~K]) -> Dict[~K, List[~T]]:
2272    def group_by_to(
2273        self, destination: Dict[K, List[T]], key_selector: Callable[..., K]
2274    ) -> Dict[K, List[T]]:
2275        """
2276        Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection
2277        and values being the corresponding elements of original collection.
2278
2279        Example 1:
2280        >>> lst = [1, 2, 3, 4, 5]
2281        >>> it(lst).group_by_to({}, lambda x: x%2)
2282        {1: [1, 3, 5], 0: [2, 4]}
2283        """
2284        key_selector = self.__callback_overload_warpper__(key_selector)
2285        for e in self:
2286            k = key_selector(e)
2287            if k not in destination:
2288                destination[k] = []
2289            destination[k].append(e)
2290        return destination

Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection and values being the corresponding elements of original collection.

Example 1:

>>> lst = [1, 2, 3, 4, 5]
>>> it(lst).group_by_to({}, lambda x: x%2)
{1: [1, 3, 5], 0: [2, 4]}
def for_each(self, action: Callable[..., NoneType]) -> None:
2298    def for_each(self, action: Callable[..., None]) -> None:
2299        """
2300        Invokes [action] function on each element of the given Stream.
2301
2302        Example 1:
2303        >>> lst = ['a', 'b', 'c']
2304        >>> it(lst).for_each(lambda x: print(x))
2305        a
2306        b
2307        c
2308
2309        Example 2:
2310        >>> lst = ['a', 'b', 'c']
2311        >>> it(lst).for_each(lambda x, i: print(x, i))
2312        a 0
2313        b 1
2314        c 2
2315        """
2316        self.on_each(action)

Invokes [action] function on each element of the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).for_each(lambda x: print(x))
a
b
c

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).for_each(lambda x, i: print(x, i))
a 0
b 1
c 2
def parallel_for_each( self, action: Callable[..., NoneType], max_workers: Optional[int] = None) -> None:
2332    def parallel_for_each(
2333        self, action: Callable[..., None], max_workers: Optional[int] = None
2334    ) -> None:
2335        """
2336        Invokes [action] function on each element of the given Stream in parallel.
2337
2338        Example 1:
2339        >>> lst = ['a', 'b', 'c']
2340        >>> it(lst).parallel_for_each(lambda x: print(x))
2341        a
2342        b
2343        c
2344
2345        Example 2:
2346        >>> lst = ['a', 'b', 'c']
2347        >>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2)
2348        a
2349        b
2350        c
2351        """
2352        self.parallel_on_each(action, max_workers)

Invokes [action] function on each element of the given Stream in parallel.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_for_each(lambda x: print(x))
a
b
c

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2)
a
b
c
def on_each(self, action: Callable[..., NoneType]) -> Stream[~T]:
2360    def on_each(self, action: Callable[..., None]) -> Stream[T]:
2361        """
2362        Invokes [action] function on each element of the given Stream.
2363
2364        Example 1:
2365        >>> lst = ['a', 'b', 'c']
2366        >>> it(lst).on_each(lambda x: print(x)) and None
2367        a
2368        b
2369        c
2370
2371        Example 2:
2372        >>> lst = ['a', 'b', 'c']
2373        >>> it(lst).on_each(lambda x, i: print(x, i)) and None
2374        a 0
2375        b 1
2376        c 2
2377        """
2378        action = self.__callback_overload_warpper__(action)
2379        for i in self:
2380            action(i)
2381        return self

Invokes [action] function on each element of the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).on_each(lambda x: print(x)) and None
a
b
c

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).on_each(lambda x, i: print(x, i)) and None
a 0
b 1
c 2
def parallel_on_each( self, action: Callable[..., NoneType], max_workers: Optional[int] = None, chunksize: int = 1, executor: "'ParallelMappingTransform.Executor'" = 'Thread') -> Stream[~T]:
2407    def parallel_on_each(
2408        self,
2409        action: Callable[..., None],
2410        max_workers: Optional[int] = None,
2411        chunksize: int = 1,
2412        executor: "ParallelMappingTransform.Executor" = "Thread",
2413    ) -> Stream[T]:
2414        """
2415        Invokes [action] function on each element of the given Stream.
2416
2417        Example 1:
2418        >>> lst = ['a', 'b', 'c']
2419        >>> it(lst).parallel_on_each(lambda x: print(x)) and None
2420        a
2421        b
2422        c
2423
2424        Example 2:
2425        >>> lst = ['a', 'b', 'c']
2426        >>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None
2427        a
2428        b
2429        c
2430        """
2431        from .parallel_mapping import ParallelMappingTransform
2432
2433        action = self.__callback_overload_warpper__(action)
2434        for _ in ParallelMappingTransform(self, action, max_workers, chunksize, executor):
2435            pass
2436        return self

Invokes [action] function on each element of the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_on_each(lambda x: print(x)) and None
a
b
c

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None
a
b
c
def zip( self, other: Iterable[Any], transform: Optional[Callable[..., ~O]] = None) -> Stream[typing.Any]:
2442    def zip(
2443        self,
2444        other: Iterable[Any],
2445        transform: Optional[Callable[..., V]] = None,  # type: ignore
2446    ) -> Stream[Any]:
2447        """
2448        Returns a new Stream of tuples, where each tuple contains two elements.
2449
2450        Example 1:
2451        >>> lst1 = ['a', 'b', 'c']
2452        >>> lst2 = [1, 2, 3]
2453        >>> it(lst1).zip(lst2).to_list()
2454        [('a', 1), ('b', 2), ('c', 3)]
2455
2456        Example 2:
2457        >>> lst1 = ['a', 'b', 'c']
2458        >>> lst2 = [1, 2, 3]
2459        >>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list()
2460        ['a__1', 'b__2', 'c__3']
2461        """
2462        if transform is None:
2463
2464            def transform(*x: Any) -> Tuple[Any, ...]:
2465                return (*x,)
2466
2467        from .merging import MergingTransform
2468
2469        return it(MergingTransform(self, other, transform))

Returns a new Stream of tuples, where each tuple contains two elements.

Example 1:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1).zip(lst2).to_list()
[('a', 1), ('b', 2), ('c', 3)]

Example 2:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list()
['a__1', 'b__2', 'c__3']
def zip_with_next( self, transform: Optional[Callable[[~T, ~T], Any]] = None) -> Stream[typing.Any]:
2475    def zip_with_next(self, transform: Optional[Callable[[T, T], Any]] = None) -> Stream[Any]:
2476        """
2477        Returns a sequence containing the results of applying the given [transform] function
2478        to an each pair of two adjacent elements in this sequence.
2479
2480        Example 1:
2481        >>> lst = ['a', 'b', 'c']
2482        >>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list()
2483        ['a__b', 'b__c']
2484
2485        Example 2:
2486        >>> lst = ['a', 'b', 'c']
2487        >>> it(lst).zip_with_next().to_list()
2488        [('a', 'b'), ('b', 'c')]
2489        """
2490        from .merging_with_next import MergingWithNextTransform
2491
2492        return it(MergingWithNextTransform(self, transform or (lambda a, b: (a, b))))

Returns a sequence containing the results of applying the given [transform] function to an each pair of two adjacent elements in this sequence.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list()
['a__b', 'b__c']

Example 2:

>>> lst = ['a', 'b', 'c']
>>> it(lst).zip_with_next().to_list()
[('a', 'b'), ('b', 'c')]
def unzip( self: Stream[typing.Tuple[~U, ~O]], transform: Union[Callable[..., Tuple[Any, Any]], NoneType, bool] = None) -> "'Tuple[ListLike[U], ListLike[V]]'":
2506    def unzip(  # type: ignore
2507        self: Stream[Tuple[U, V]],
2508        transform: Union[Optional[Callable[..., Tuple[Any, Any]]], bool] = None,
2509    ) -> "Tuple[ListLike[U], ListLike[V]]":
2510        """
2511        Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array.
2512
2513        Example 1:
2514        >>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}]
2515        >>> a, b = it(lst).unzip(lambda x: (x['name'], x['age']))
2516        >>> a
2517        ['a', 'b', 'c']
2518        >>> b
2519        [11, 12, 13]
2520
2521        Example 1:
2522        >>> lst = [('a', 11), ('b', 12), ('c', 13)]
2523        >>> a, b = it(lst).unzip()
2524        >>> a
2525        ['a', 'b', 'c']
2526        >>> b
2527        [11, 12, 13]
2528        """
2529        from .list_like import ListLike
2530
2531        it = self
2532        if isinstance(transform, bool):
2533            transform = None
2534
2535        if transform is not None:
2536            transform = self.__callback_overload_warpper__(transform)
2537            it = it.map(transform)
2538
2539        a = it.map(lambda x: x[0])  # type: ignore
2540        b = it.map(lambda x: x[1])  # type: ignore
2541
2542        return ListLike(a), ListLike(b)

Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array.

Example 1:

>>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}]
>>> a, b = it(lst).unzip(lambda x: (x['name'], x['age']))
>>> a
['a', 'b', 'c']
>>> b
[11, 12, 13]

Example 1:

>>> lst = [('a', 11), ('b', 12), ('c', 13)]
>>> a, b = it(lst).unzip()
>>> a
['a', 'b', 'c']
>>> b
[11, 12, 13]
def with_index(self) -> Stream[IndexedValue[~T]]:
2544    def with_index(self) -> Stream[IndexedValue[T]]:
2545        """
2546        Returns a sequence containing the elements of this sequence and their indexes.
2547
2548        Example 1:
2549        >>> lst = ['a', 'b', 'c']
2550        >>> it(lst).with_index().to_list()
2551        [IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)]
2552        """
2553        return self.indexed()

Returns a sequence containing the elements of this sequence and their indexes.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).with_index().to_list()
[IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)]
def shuffled( self, seed: "Union['Random', int, float, str, bytes, bytearray, None]" = None) -> Stream[~T]:
2561    def shuffled(  # type: ignore
2562        self, seed: Union["Random", int, float, str, bytes, bytearray, None] = None
2563    ) -> Stream[T]:
2564        """
2565        Returns a sequence that yields elements of this sequence randomly shuffled
2566        using the specified [random] instance as the source of randomness.
2567
2568        Example 1:
2569        >>> lst = ['a', 'b', 'c']
2570        >>> it(lst).shuffled('123').to_list()
2571        ['b', 'a', 'c']
2572
2573        Example 2:
2574        >>> from random import Random
2575        >>> lst = ['a', 'b', 'c']
2576        >>> it(lst).shuffled(Random('123')).to_list()
2577        ['b', 'a', 'c']
2578
2579        Example 3:
2580        >>> lst = ['a', 'b', 'c']
2581        >>> it(lst).shuffled(123).to_list()
2582        ['c', 'b', 'a']
2583        """
2584        from .shuffling import ShufflingTransform
2585
2586        return it(ShufflingTransform(self, seed))

Returns a sequence that yields elements of this sequence randomly shuffled using the specified [random] instance as the source of randomness.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled('123').to_list()
['b', 'a', 'c']

Example 2:

>>> from random import Random
>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled(Random('123')).to_list()
['b', 'a', 'c']

Example 3:

>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled(123).to_list()
['c', 'b', 'a']
def partition( self, predicate: Callable[..., bool]) -> "'Tuple[ListLike[T], ListLike[T]]'":
2598    def partition(self, predicate: Callable[..., bool]) -> "Tuple[ListLike[T], ListLike[T]]":
2599        """
2600        Partitions the elements of the given Stream into two groups,
2601        the first group containing the elements for which the predicate returns true,
2602        and the second containing the rest.
2603
2604        Example 1:
2605        >>> lst = ['a', 'b', 'c', '2']
2606        >>> it(lst).partition(lambda x: x.isalpha())
2607        (['a', 'b', 'c'], ['2'])
2608
2609        Example 2:
2610        >>> lst = ['a', 'b', 'c', '2']
2611        >>> it(lst).partition(lambda _, i: i % 2 == 0)
2612        (['a', 'c'], ['b', '2'])
2613        """
2614        from .list_like import ListLike
2615
2616        predicate_a = self.__callback_overload_warpper__(predicate)
2617        predicate_b = self.__callback_overload_warpper__(predicate)
2618        part_a = self.filter(predicate_a)
2619        part_b = self.filter(lambda x: not predicate_b(x))
2620        return ListLike(part_a), ListLike(part_b)

Partitions the elements of the given Stream into two groups, the first group containing the elements for which the predicate returns true, and the second containing the rest.

Example 1:

>>> lst = ['a', 'b', 'c', '2']
>>> it(lst).partition(lambda x: x.isalpha())
(['a', 'b', 'c'], ['2'])

Example 2:

>>> lst = ['a', 'b', 'c', '2']
>>> it(lst).partition(lambda _, i: i % 2 == 0)
(['a', 'c'], ['b', '2'])
def indexed(self) -> Stream[IndexedValue[~T]]:
2622    def indexed(self) -> Stream[IndexedValue[T]]:
2623        return self.map(lambda x, i: IndexedValue(x, i))
def combinations(self, n: int) -> Stream[typing.Tuple[~T, ...]]:
2633    def combinations(self, n: int) -> Stream[Tuple[T, ...]]:
2634        """
2635        Returns a Stream of all possible combinations of size [n] from the given Stream.
2636
2637        Example 1:
2638        >>> lst = ['a', 'b', 'c']
2639        >>> it(lst).combinations(2).to_list()
2640        [('a', 'b'), ('a', 'c'), ('b', 'c')]
2641        """
2642        from .combination import CombinationTransform
2643
2644        return it(CombinationTransform(self, n))

Returns a Stream of all possible combinations of size [n] from the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).combinations(2).to_list()
[('a', 'b'), ('a', 'c'), ('b', 'c')]
def nth(self, n: int) -> ~T:
2646    def nth(self, n: int) -> T:
2647        """
2648        Returns the nth element of the given Stream.
2649
2650        Example 1:
2651        >>> lst = ['a', 'b', 'c']
2652        >>> it(lst).nth(2)
2653        'c'
2654        """
2655        return self.skip(n).first()

Returns the nth element of the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).nth(2)
'c'
def windowed( self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[typing.List[~T]]:
2657    def windowed(self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[List[T]]:
2658        """
2659         Returns a Stream of all possible sliding windows of size [size] from the given Stream.
2660
2661        Example 1:
2662        >>> lst = ['a', 'b', 'c', 'd', 'e']
2663        >>> it(lst).windowed(3).to_list()
2664        [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
2665
2666        Example 2:
2667        >>> lst = ['a', 'b', 'c', 'd', 'e']
2668        >>> it(lst).windowed(3, 2).to_list()
2669        [['a', 'b', 'c'], ['c', 'd', 'e']]
2670
2671        Example 3:
2672        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2673        >>> it(lst).windowed(3, 2, True).to_list()
2674        [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']]
2675        """
2676        from .windowed import WindowedTransform
2677
2678        return it(WindowedTransform(self, size, step, partialWindows))

Returns a Stream of all possible sliding windows of size [size] from the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst)pyiter.windowed(3).to_list()
[['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]

Example 2:

>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst)pyiter.windowed(3, 2).to_list()
[['a', 'b', 'c'], ['c', 'd', 'e']]

Example 3:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> it(lst)pyiter.windowed(3, 2, True).to_list()
[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']]
def chunked(self, size: int) -> Stream[typing.List[~T]]:
2680    def chunked(self, size: int) -> Stream[List[T]]:
2681        """
2682        Returns a Stream of all possible chunks of size [size] from the given Stream.
2683
2684        Example 1:
2685        >>> lst = ['a', 'b', 'c', 'd', 'e']
2686        >>> it(lst).chunked(3).to_list()
2687        [['a', 'b', 'c'], ['d', 'e']]
2688
2689
2690        Example 2:
2691        >>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
2692        >>> it(lst).chunked(3).to_list()
2693        [['a', 'b', 'c'], ['d', 'e', 'f']]
2694        """
2695        return self.windowed(size, size, True)

Returns a Stream of all possible chunks of size [size] from the given Stream.

Example 1:

>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst).chunked(3).to_list()
[['a', 'b', 'c'], ['d', 'e']]

Example 2:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> it(lst).chunked(3).to_list()
[['a', 'b', 'c'], ['d', 'e', 'f']]
def repeat(self, n: int) -> Stream[~T]:
2697    def repeat(self, n: int) -> Stream[T]:
2698        """
2699        Returns a Stream containing this sequence repeated n times.
2700
2701        Example 1:
2702        >>> lst = ['a', 'b']
2703        >>> it(lst).repeat(3).to_list()
2704        ['a', 'b', 'a', 'b', 'a', 'b']
2705        """
2706        from .concat import ConcatTransform
2707
2708        return it(ConcatTransform([self] * n))

Returns a Stream containing this sequence repeated n times.

Example 1:

>>> lst = ['a', 'b']
>>> it(lst).repeat(3).to_list()
['a', 'b', 'a', 'b', 'a', 'b']
def concat(self, *other: Iterable[~T]) -> Stream[~T]:
2710    def concat(self, *other: Iterable[T]) -> Stream[T]:
2711        """
2712        Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream.
2713
2714        Example 1:
2715        >>> lst1 = ['a', 'b', 'c']
2716        >>> lst2 = [1, 2, 3]
2717        >>> it(lst1).concat(lst2).to_list()
2718        ['a', 'b', 'c', 1, 2, 3]
2719
2720        Example 2:
2721        >>> lst1 = ['a', 'b', 'c']
2722        >>> lst2 = [1, 2, 3]
2723        >>> lst3 = [4, 5, 6]
2724        >>> it(lst1).concat(lst2, lst3).to_list()
2725        ['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
2726        """
2727        from .concat import ConcatTransform
2728
2729        return it(ConcatTransform([self, *other]))

Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream.

Example 1:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1)pyiter.concat(lst2).to_list()
['a', 'b', 'c', 1, 2, 3]

Example 2:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> lst3 = [4, 5, 6]
>>> it(lst1)pyiter.concat(lst2, lst3).to_list()
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
def intersect(self, *other: Iterable[~T]) -> Stream[~T]:
2731    def intersect(self, *other: Iterable[T]) -> Stream[T]:
2732        """
2733        Returns a set containing all elements that are contained by both this collection and the specified collection.
2734
2735        The returned set preserves the element iteration order of the original collection.
2736
2737        To get a set containing all elements that are contained at least in one of these collections use union.
2738
2739        Example 1:
2740        >>> lst1 = ['a', 'b', 'c']
2741        >>> lst2 = ['a2', 'b2', 'c']
2742        >>> it(lst1).intersect(lst2).to_list()
2743        ['c']
2744
2745        Example 2:
2746        >>> lst1 = ['a', 'b', 'c']
2747        >>> lst2 = ['a2', 'b', 'c']
2748        >>> lst3 = ['a3', 'b', 'c3']
2749        >>> it(lst1).intersect(lst2, lst3).to_list()
2750        ['b']
2751
2752
2753        Example 1:
2754        >>> lst1 = ['a', 'a', 'c']
2755        >>> lst2 = ['a2', 'b2', 'a']
2756        >>> it(lst1).intersect(lst2).to_list()
2757        ['a']
2758        """
2759        from .intersection import IntersectionTransform
2760
2761        return it(IntersectionTransform([self, *other]))

Returns a set containing all elements that are contained by both this collection and the specified collection.

The returned set preserves the element iteration order of the original collection.

To get a set containing all elements that are contained at least in one of these collections use union.

Example 1:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b2', 'c']
>>> it(lst1).intersect(lst2).to_list()
['c']

Example 2:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b', 'c']
>>> lst3 = ['a3', 'b', 'c3']
>>> it(lst1).intersect(lst2, lst3).to_list()
['b']

Example 1:

>>> lst1 = ['a', 'a', 'c']
>>> lst2 = ['a2', 'b2', 'a']
>>> it(lst1).intersect(lst2).to_list()
['a']
def union(self, *other: Stream[~T]) -> Stream[~T]:
2763    def union(self, *other: Stream[T]) -> Stream[T]:
2764        """
2765        Returns a set containing all distinct elements from both collections.
2766
2767        The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.
2768
2769        To get a set containing all elements that are contained in both collections use intersect.
2770
2771        Example 1:
2772        >>> lst1 = ['a', 'b', 'c']
2773        >>> lst2 = ['a2', 'b2', 'c']
2774        >>> it(lst1).union(lst2).to_list()
2775        ['a', 'b', 'c', 'a2', 'b2']
2776
2777        Example 2:
2778        >>> lst1 = ['a', 'b', 'c']
2779        >>> lst2 = ['a2', 'b', 'c']
2780        >>> lst3 = ['a3', 'b', 'c3']
2781        >>> it(lst1).union(lst2, lst3).to_list()
2782        ['a', 'b', 'c', 'a2', 'a3', 'c3']
2783
2784
2785        Example 1:
2786        >>> lst1 = ['a', 'a', 'c']
2787        >>> lst2 = ['a2', 'b2', 'a']
2788        >>> it(lst1).union(lst2).to_list()
2789        ['a', 'c', 'a2', 'b2']
2790        """
2791        return self.concat(*other).distinct()

Returns a set containing all distinct elements from both collections.

The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.

To get a set containing all elements that are contained in both collections use intersect.

Example 1:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b2', 'c']
>>> it(lst1).union(lst2).to_list()
['a', 'b', 'c', 'a2', 'b2']

Example 2:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b', 'c']
>>> lst3 = ['a3', 'b', 'c3']
>>> it(lst1).union(lst2, lst3).to_list()
['a', 'b', 'c', 'a2', 'a3', 'c3']

Example 1:

>>> lst1 = ['a', 'a', 'c']
>>> lst2 = ['a2', 'b2', 'a']
>>> it(lst1).union(lst2).to_list()
['a', 'c', 'a2', 'b2']
def join(self: Stream[str], separator: str = ' ') -> str:
2793    def join(self: Stream[str], separator: str = " ") -> str:
2794        """
2795        Joins the elements of the given Stream into a string.
2796
2797        Example 1:
2798        >>> lst = ['a', 'b', 'c']
2799        >>> it(lst).join(', ')
2800        'a, b, c'
2801        """
2802        return separator.join(self)

Joins the elements of the given Stream into a string.

Example 1:

>>> lst = ['a', 'b', 'c']
>>> it(lst).join(', ')
'a, b, c'
def progress( self, progress_func: Union[Callable[[Stream[~T]], Iterable[~T]], Literal['tqdm'], Literal['tqdm_rich'], NoneType] = None) -> Stream[~T]:
2812    def progress(
2813        self,
2814        progress_func: Union[
2815            Callable[[Stream[T]], Iterable[T]],
2816            Literal["tqdm"],
2817            Literal["tqdm_rich"],
2818            None,
2819        ] = None,
2820    ) -> Stream[T]:
2821        """
2822        Returns a Stream that enable a progress bar for the given Stream.
2823
2824        Example 1:
2825        >>> from tqdm import tqdm
2826        >>> from time import sleep
2827        >>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None
2828        >>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass
2829        """
2830        if progress_func is not None and callable(progress_func):
2831            return it(progress_func(self))
2832
2833        def import_tqdm():
2834            if progress_func == "tqdm_rich":
2835                import warnings
2836                from tqdm.rich import tqdm
2837                from tqdm import TqdmExperimentalWarning
2838
2839                warnings.filterwarnings("ignore", category=TqdmExperimentalWarning)
2840            else:
2841                from tqdm import tqdm
2842            return tqdm
2843
2844        try:
2845            tqdm = import_tqdm()
2846        except ImportError:
2847            from pip import main as pip  # type: ignore
2848
2849            pip(["install", "tqdm"])
2850            tqdm = import_tqdm()
2851
2852        return it(tqdm(self, total=len(self)))

Returns a Stream that enable a progress bar for the given Stream.

Example 1:

>>> from tqdm import tqdm
>>> from time import sleep
>>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None
>>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass
def typing_as(self, typ: Type[~U]) -> Stream[~U]:
2854    def typing_as(self, typ: Type[U]) -> Stream[U]:
2855        """
2856        Cast the element as specific Type to gain code completion base on type annotations.
2857        """
2858        el = self.first_not_none_of_or_none()
2859        if el is None or isinstance(el, typ) or not isinstance(el, dict):
2860            return self  # type: ignore
2861
2862        class AttrDict(Dict[str, Any]):
2863            def __init__(self, value: Dict[str, Any]) -> None:
2864                super().__init__(**value)
2865                setattr(self, "__dict__", value)
2866                self.__getattr__ = value.__getitem__
2867                self.__setattr__ = value.__setattr__  # type: ignore
2868
2869        return self.map(AttrDict)  # type: ignore  # use https://github.com/cdgriffith/Box ?

Cast the element as specific Type to gain code completion base on type annotations.

def to_set(self) -> Set[~T]:
2871    def to_set(self) -> Set[T]:
2872        """
2873        Returns a set containing all elements of this Stream.
2874
2875        Example 1:
2876        >>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'}
2877        True
2878        """
2879        return set(self)

Returns a set containing all elements of this Stream.

Example 1:

>>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'}
True
def to_dict( self, transform: Optional[Callable[..., Tuple[~K, ~O]]] = None) -> Dict[~K, ~O]:
2889    def to_dict(self, transform: Optional[Callable[..., Tuple[K, V]]] = None) -> Dict[K, V]:
2890        """
2891        Returns a [Dict] containing key-value Tuple provided by [transform] function
2892        applied to elements of the given Stream.
2893
2894        Example 1:
2895        >>> lst = ['1', '2', '3']
2896        >>> it(lst).to_dict(lambda x: (int(x), x))
2897        {1: '1', 2: '2', 3: '3'}
2898
2899        Example 2:
2900        >>> lst = [(1, '1'), (2, '2'), (3, '3')]
2901        >>> it(lst).to_dict()
2902        {1: '1', 2: '2', 3: '3'}
2903        """
2904        return self.associate(transform or (lambda x: x))  # type: ignore

Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.

Example 1:

>>> lst = ['1', '2', '3']
>>> it(lst).to_dict(lambda x: (int(x), x))
{1: '1', 2: '2', 3: '3'}

Example 2:

>>> lst = [(1, '1'), (2, '2'), (3, '3')]
>>> it(lst).to_dict()
{1: '1', 2: '2', 3: '3'}
def to_list(self) -> List[~T]:
2906    def to_list(self) -> List[T]:
2907        """
2908        Returns a list with elements of the given Stream.
2909
2910        Example 1:
2911        >>> it(['b', 'c', 'a']).to_list()
2912        ['b', 'c', 'a']
2913        """
2914        if self.__transform__.cache is not None:
2915            return self.__transform__.cache.copy()
2916        return [s for s in self]

Returns a list with elements of the given Stream.

Example 1:

>>> it(['b', 'c', 'a']).to_list()
['b', 'c', 'a']
async def to_list_async(self: Iterable[Awaitable[~T]]) -> List[~T]:
2918    async def to_list_async(self: Iterable[Awaitable[T]]) -> List[T]:
2919        """
2920        Returns a list with elements of the given Stream.
2921
2922        Example 1:
2923        >>> it(['b', 'c', 'a']).to_list()
2924        ['b', 'c', 'a']
2925        """
2926        from asyncio import gather
2927
2928        return await gather(*self)  # type: ignore

Returns a list with elements of the given Stream.

Example 1:

>>> it(['b', 'c', 'a']).to_list()
['b', 'c', 'a']
def let(self, block: Callable[[Stream[~T]], ~U]) -> ~U:
2930    def let(self, block: Callable[[Stream[T]], U]) -> U:
2931        """
2932        Calls the specified function [block] with `self` value as its argument and returns its result.
2933
2934        Example 1:
2935        >>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list()
2936        ['a!', 'b!', 'c!']
2937        """
2938        return block(self)

Calls the specified function [block] with self value as its argument and returns its result.

Example 1:

>>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list()
['a!', 'b!', 'c!']
def also( self, block: Callable[[Stream[~T]], Any]) -> Stream[~T]:
2940    def also(self, block: Callable[[Stream[T]], Any]) -> Stream[T]:
2941        """
2942        Calls the specified function [block] with `self` value as its argument and returns `self` value.
2943
2944        Example 1:
2945        >>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list()
2946        ['a', 'b', 'c']
2947        """
2948        block(self)
2949        return self

Calls the specified function [block] with self value as its argument and returns self value.

Example 1:

>>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list()
['a', 'b', 'c']
size: int
2951    @property
2952    def size(self) -> int:
2953        """
2954        Returns the size of the given Stream.
2955        """
2956        return len(self.data)

Returns the size of the given Stream.

def is_empty(self) -> bool:
2958    def is_empty(self) -> bool:
2959        """
2960        Returns True if the Stream is empty, False otherwise.
2961
2962        Example 1:
2963        >>> it(['a', 'b', 'c']).is_empty()
2964        False
2965
2966        Example 2:
2967        >>> it([None]).is_empty()
2968        False
2969
2970        Example 3:
2971        >>> it([]).is_empty()
2972        True
2973        """
2974        return id(self.first_or_default(self)) == id(self)

Returns True if the Stream is empty, False otherwise.

Example 1:

>>> it(['a', 'b', 'c']).is_empty()
False

Example 2:

>>> it([None]).is_empty()
False

Example 3:

>>> it([]).is_empty()
True
def iter(self) -> Iterator[~T]:
2979    def iter(self) -> Iterator[T]:
2980        return self.__do_iter__()
class AutoIncrementIndex:
3035class AutoIncrementIndex:
3036    idx = 0
3037
3038    def __call__(self) -> int:
3039        val = self.idx
3040        self.idx += 1
3041        return val
idx = 0
class IndexedValue(typing.NamedTuple, typing.Generic[~T]):
3044class IndexedValue(NamedTuple, Generic[T]):
3045    val: T
3046    idx: int
3047
3048    def __repr__(self) -> str:
3049        return f"IndexedValue({self.idx}, {self.val})"

IndexedValue(val, idx)

IndexedValue(val: ForwardRef('T'), idx: int)

Create new instance of IndexedValue(val, idx)

val: ~T

Alias for field number 0

idx: int

Alias for field number 1

def throw(exception: Exception) -> Any:
3052def throw(exception: Exception) -> Any:
3053    raise exception
def none_or(value: Optional[~T], default: ~T) -> ~T:
3056def none_or(value: Optional[T], default: T) -> T:
3057    return value if value is not None else default
def none_or_else(value: Optional[~T], f: Callable[[], ~T]) -> ~T:
3060def none_or_else(value: Optional[T], f: Callable[[], T]) -> T:
3061    return value if value is not None else f()
def is_debugging() -> bool:
3064def is_debugging() -> bool:
3065    from inspect import currentframe
3066    from traceback import walk_stack
3067
3068    return (
3069        it(walk_stack(currentframe()))
3070        .take(20)
3071        .map(lambda s: s[0])
3072        .any(
3073            lambda s: (
3074                s.f_code.co_name == "get_contents_debug_adapter_protocol"
3075                and "pydevd_resolver.py" in s.f_code.co_filename
3076            )
3077        )
3078    )
class StreamProducer:
3081class StreamProducer:
3082    @overload
3083    def __call__(self, elements: List[T]) -> Stream[T]: ...
3084    @overload
3085    def __call__(self, elements: Iterable[T]) -> Stream[T]: ...
3086    @overload
3087    def __call__(self, *elements: T) -> Stream[T]: ...
3088    def __call__(self, *iterable: Union[Iterable[T], List[T], T]) -> Stream[T]:  # type: ignore
3089        if len(iterable) == 1:
3090            iter = iterable[0]
3091            if isinstance(iter, Stream):
3092                return iter  # type: ignore
3093            if isinstance(iter, Iterable) and not isinstance(iter, str):
3094                return Stream(iter)  # type: ignore
3095        return Stream(iterable)  # type: ignore
3096
3097    def json(self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[Any]:
3098        """
3099        Reads and parses the input of a json file.
3100        """
3101        import json
3102
3103        with open(filepath, "r") as f:
3104            data = json.load(f, **kwargs)  # type: ignore
3105            return self(data)
3106
3107    def csv(self, filepath: str) -> Stream[List[str]] | Stream[Dict[str, str]]:
3108        """
3109        Reads and parses the input of a csv file.
3110        """
3111        return self.read_csv(filepath)
3112
3113    def read_csv(
3114        self, filepath: str, header: Optional[int] = 0
3115    ) -> Stream[List[str]] | Stream[Dict[str, str]]:
3116        """
3117        Reads and parses the input of a csv file.
3118
3119        Example 1:
3120        >>> it.read_csv('tests/data/a.csv').to_list()
3121        [{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}]
3122        """
3123        import csv
3124
3125        it = self
3126        with open(filepath) as f:
3127            reader = csv.reader(f)
3128            iter = it(*reader)
3129            if header is None or header < 0:
3130                return iter
3131
3132            headers = iter.element_at_or_none(header)
3133            if headers is not None:
3134                if header == 0:
3135                    iter = iter.skip(1)
3136                else:
3137                    iter = iter.filter(lambda _, i: i != header)
3138
3139                return iter.map(
3140                    lambda row: it(row).associate_by(
3141                        lambda _, ordinal: (
3142                            headers[ordinal] if ordinal < len(headers) else f"undefined_{ordinal}"
3143                        )
3144                    )
3145                )
3146            return iter
3147
3148    def __repr__(self) -> str:
3149        return __package__ or self.__class__.__name__
def json( self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[typing.Any]:
3097    def json(self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[Any]:
3098        """
3099        Reads and parses the input of a json file.
3100        """
3101        import json
3102
3103        with open(filepath, "r") as f:
3104            data = json.load(f, **kwargs)  # type: ignore
3105            return self(data)

Reads and parses the input of a json file.

def csv( self, filepath: str) -> Stream[typing.List[str]] | Stream[typing.Dict[str, str]]:
3107    def csv(self, filepath: str) -> Stream[List[str]] | Stream[Dict[str, str]]:
3108        """
3109        Reads and parses the input of a csv file.
3110        """
3111        return self.read_csv(filepath)

Reads and parses the input of a csv file.

def read_csv( self, filepath: str, header: Optional[int] = 0) -> Stream[typing.List[str]] | Stream[typing.Dict[str, str]]:
3113    def read_csv(
3114        self, filepath: str, header: Optional[int] = 0
3115    ) -> Stream[List[str]] | Stream[Dict[str, str]]:
3116        """
3117        Reads and parses the input of a csv file.
3118
3119        Example 1:
3120        >>> it.read_csv('tests/data/a.csv').to_list()
3121        [{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}]
3122        """
3123        import csv
3124
3125        it = self
3126        with open(filepath) as f:
3127            reader = csv.reader(f)
3128            iter = it(*reader)
3129            if header is None or header < 0:
3130                return iter
3131
3132            headers = iter.element_at_or_none(header)
3133            if headers is not None:
3134                if header == 0:
3135                    iter = iter.skip(1)
3136                else:
3137                    iter = iter.filter(lambda _, i: i != header)
3138
3139                return iter.map(
3140                    lambda row: it(row).associate_by(
3141                        lambda _, ordinal: (
3142                            headers[ordinal] if ordinal < len(headers) else f"undefined_{ordinal}"
3143                        )
3144                    )
3145                )
3146            return iter

Reads and parses the input of a csv file.

Example 1:

>>> it.read_csv('tests/data/a.csv').to_list()
[{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}]
it: StreamProducer = pyiter

Creates an iterator from a list of elements or given Iterable.

Example 1:
>>> it('hello', 'world').map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 2:
>>> it(['hello', 'world']).map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 3:
>>> it(range(10)).map(lambda x: x*x).to_list()
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]