Skip to content

QList

Bases: list

QList is a python list extension that adds several chainable, lazy evaluated methods to the standard list.

Found in qwlist.QList

Source code in src\qwlist\qwlist.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
class QList(list):
    """
    `QList` is a python list extension that adds several chainable, lazy
    evaluated methods to the standard `list`.

    Found in `qwlist.QList`
    """

    @overload
    def __getitem__(self, item: slice) -> "QList[T]":
        ...

    @overload
    def __getitem__(self, item: int) -> T:
        ...

    def __getitem__(self, item):
        if isinstance(item, slice):
            return QList(super().__getitem__(item))
        return super().__getitem__(item)

    def slice(self, s: slice) -> Lazy[T]:
        """
        Calling this method with `s` equal to `slice(3)` works similarly to
        `list[:3]` but is lazy evaluated.

        Args:
            s: slice object

        Returns: `Lazy[T]`
        """
        assert isinstance(s, slice), f"slice method argument must be a slice object. Got {type(s)}."

        def inner():
            for elem in self[s]:
                yield elem
        return Lazy(inner())

    def list(self) -> list[T]:
        """
        Changes `QList` into `list`.

        Returns: `list[T]`
        """
        return list(self)

    def eager(self) -> "EagerQList[T]":
        """
        Changes `QList` into `EagerQList`.

        Returns: `EagerQList[T]`
        """
        from .eager import EagerQList
        return EagerQList(self)

    def filter(self, pred: Callable[[T], bool]) -> Lazy[T]:
        """
        Returns a `Lazy` object containing all values from the `QList` for which
        the predicate holds true.

        Args:
             pred: `function (T) -> bool`

        Returns: `Lazy[T]`

        Examples:
            >>> QList([1, 2, 3, 4]).filter(lambda x: x < 3).collect()
            [1, 2]
        """
        def inner():
            for elem in self:
                if pred(elem):
                    yield elem
        return Lazy(inner())

    def map(self, mapper: Callable[[T], K]) -> Lazy[K]:
        """
        Returns a `Lazy` object containing all values from `QList` with
        the mapping function applied on them.

        Args:
            mapper: `function: (T) -> K`

        Returns: `Lazy[K]`
        """
        def inner():
            for elem in self:
                yield mapper(elem)
        return Lazy(inner())

    def foreach(self, action: Callable[[T], None]):
        """
        Applies the given function to each of the `QList` elements.

        Args:
            action: `function (T) -> None`

        Returns: `None`
        """
        for elem in self:
            action(elem)

    def fold(self, operation: Callable[[K, T], K], init: K) -> K:
        """
        Given the combination operator reduces the `QList` by processing
        its values, building up the final value.

        **Other names:** fold_left, reduce, accumulate, aggregate

        Args:
            operation: `function: (K, T) -> K`
                Given the initial value `init` applies the
                given combination operator on each element of the `QList`,
                treating the result as a first argument in the next step.
            init: initial value for the combination operator.

        Returns: `K`

        Examples:
            >>> QList([1, 2, 3]).fold(lambda acc, x: acc + x, 0)
            6
        """
        acc = init
        for elem in self:
            acc = operation(acc, elem)
        return acc

    def fold_right(self, operation: Callable[[K, T], K], init: K) -> K:
        """
        Given the combination operator reduces the `QList` by processing
        its values, building up the final value.

        Args:
            operation: `function: (K, T) -> K`
                Given the initial value `init` applies the
                given combination operator on each element of the `QList`, starting from the
                last element, treating the result as a first argument in the next step.
            init: initial value for the combination operator.

        Returns: `K`

        Examples:
            >>> QList([1, 2, 3]).fold_right(lambda acc, x: acc + x, 0)
            6
        """
        acc = init
        for elem in self[::-1]:
            acc = operation(acc, elem)
        return acc

    def len(self) -> int:
        """
        Returns the len of the `QList`

        (time complexity: `O(1)`)

        Returns: int
        """
        return len(self)

    def flatmap(self, mapper: Callable[[T], Iterable[K]]) -> Lazy[K]:
        """
        Applies the mapper function to each element of the `QList` and flattens the results.

        Args:
            mapper: `function (T) -> Iterable[K]`

        Returns: `Lazy[K]`

        Examples:
            >>> QList([1, 2]).flatmap(lambda x: [x, x]).qlist()
            [1, 1, 2, 2]
        """
        def inner():
            for elem in self:
                yield from mapper(elem)
        return Lazy(inner())

    def zip(self, other: Iterable[K]) -> Lazy[tuple[T, K]]:
        """
        Combines this `QList` with the given `Iterable` elementwise as tuples.
         The returned `Lazy` objects yields at most the number of elements of
         the shorter sequence (`self` or `Iterable`).

        Args:
            other: iterable to zip with this `QList`.

        Returns: `Lazy[tuple[T, K]]`

        Examples:
            >>> Lazy([1, 2, 3]).zip(['a', 'b', 'c']).collect()
            [(1, 'a'), (2, 'b'), (3, 'c')]
        """
        return Lazy(zip(self, other))

    def sorted(self, key: Callable[[T], SupportsLessThan] = None, reverse: bool = False) -> "QList[T]":
        """
        Returns a new `QList` containing all items from the original list in ascending order.

        A custom key function can be supplied to customize the sort order, and the reverse
        flag can be set to request the result in descending order.

        Args:
            key: `function (T) -> SupportsLessThan`. Defaults to `None`
            reverse: if set to `True` sorts values in descending order. Defaults to `False`

        Returns: `QList[T]`
        """
        return QList(sorted(self, key=key, reverse=reverse))

    def skip(self, n: int) -> Lazy[T]:
        """
        Skips n first elements of the QList.

        Args:
            n: numbers of elements to skip. Should be non-negative

        Returns: Lazy[T]

        Examples:
            >>> QList(range(10)).skip(2).collect()
            [2, 3, 4, 5, 6, 7, 8, 9]
        """
        def inner():
            for i, elem in enumerate(self):
                if i >= n:
                    yield elem
        return Lazy(inner())

    def take(self, n: int) -> Lazy[T]:
        """
        Takes n first elements of the QList.

        Args:
            n: int - numbers of elements to take. Should be non-negative

        Returns: Lazy[T]

        Examples:
            >>> QList(range(10)).take(2).collect()
            [0, 1]
        """
        def inner():
            for i, elem in enumerate(self):
                if i >= n:
                    return None
                yield elem
        return Lazy(inner())

    def flatten(self) -> Lazy[T]:
        """
        If self is a QList of Iterable[T] flatten concatenates all iterables into a
        single list and returns a Lazy[T] object
        Returns: Lazy[T]
        """
        def inner():
            for elem in self:
                yield from elem
        return Lazy(inner())

    def cycle(self) -> Lazy[T]:
        """
        Returns a `Lazy[T]` that cycles through the elements of the `QList` that means
        on achieving the last element the iteration starts from the beginning. The
        returned `Lazy` object has no end (infinite iterator) unless the `QList` is empty
        in which case cycle returns an empty `Lazy` object (empty iterator).

        Returns: Lazy[T]

        Examples:
            >>> QList([1, 2, 3]).cycle().take(7).collect()
            [1, 2, 3, 1, 2, 3, 1]
        """
        def inner():
            saved = []
            for elem in self:
                saved.append(elem)
                yield elem
            while saved:
                for elem in saved:
                    yield elem
        return Lazy(inner())

    def enumerate(self, start: int = 0) -> Lazy[tuple[int, T]]:
        """
        Returns a `Lazy` object with index-value pairs as its elements. Index starts at
        the given position `start` (defaults to 0).

        Returns: Lazy[tuple[int, T]]

        Examples:
            >>> QList(['a', 'b', 'c']).enumerate().collect()
            [(0, 'a'), (1, 'b'), (2, 'c')]
        """
        def inner():
            for i, elem in enumerate(self, start=start):
                yield i, elem
        return Lazy(inner())

cycle()

Returns a Lazy[T] that cycles through the elements of the QList that means on achieving the last element the iteration starts from the beginning. The returned Lazy object has no end (infinite iterator) unless the QList is empty in which case cycle returns an empty Lazy object (empty iterator).

Returns: Lazy[T]

Examples:

>>> QList([1, 2, 3]).cycle().take(7).collect()
[1, 2, 3, 1, 2, 3, 1]
Source code in src\qwlist\qwlist.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def cycle(self) -> Lazy[T]:
    """
    Returns a `Lazy[T]` that cycles through the elements of the `QList` that means
    on achieving the last element the iteration starts from the beginning. The
    returned `Lazy` object has no end (infinite iterator) unless the `QList` is empty
    in which case cycle returns an empty `Lazy` object (empty iterator).

    Returns: Lazy[T]

    Examples:
        >>> QList([1, 2, 3]).cycle().take(7).collect()
        [1, 2, 3, 1, 2, 3, 1]
    """
    def inner():
        saved = []
        for elem in self:
            saved.append(elem)
            yield elem
        while saved:
            for elem in saved:
                yield elem
    return Lazy(inner())

eager()

Changes QList into EagerQList.

Returns: EagerQList[T]

Source code in src\qwlist\qwlist.py
313
314
315
316
317
318
319
320
def eager(self) -> "EagerQList[T]":
    """
    Changes `QList` into `EagerQList`.

    Returns: `EagerQList[T]`
    """
    from .eager import EagerQList
    return EagerQList(self)

enumerate(start=0)

Returns a Lazy object with index-value pairs as its elements. Index starts at the given position start (defaults to 0).

Returns: Lazy[tuple[int, T]]

Examples:

>>> QList(['a', 'b', 'c']).enumerate().collect()
[(0, 'a'), (1, 'b'), (2, 'c')]
Source code in src\qwlist\qwlist.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def enumerate(self, start: int = 0) -> Lazy[tuple[int, T]]:
    """
    Returns a `Lazy` object with index-value pairs as its elements. Index starts at
    the given position `start` (defaults to 0).

    Returns: Lazy[tuple[int, T]]

    Examples:
        >>> QList(['a', 'b', 'c']).enumerate().collect()
        [(0, 'a'), (1, 'b'), (2, 'c')]
    """
    def inner():
        for i, elem in enumerate(self, start=start):
            yield i, elem
    return Lazy(inner())

filter(pred)

Returns a Lazy object containing all values from the QList for which the predicate holds true.

Parameters:

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

function (T) -> bool

required

Returns: Lazy[T]

Examples:

>>> QList([1, 2, 3, 4]).filter(lambda x: x < 3).collect()
[1, 2]
Source code in src\qwlist\qwlist.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def filter(self, pred: Callable[[T], bool]) -> Lazy[T]:
    """
    Returns a `Lazy` object containing all values from the `QList` for which
    the predicate holds true.

    Args:
         pred: `function (T) -> bool`

    Returns: `Lazy[T]`

    Examples:
        >>> QList([1, 2, 3, 4]).filter(lambda x: x < 3).collect()
        [1, 2]
    """
    def inner():
        for elem in self:
            if pred(elem):
                yield elem
    return Lazy(inner())

flatmap(mapper)

Applies the mapper function to each element of the QList and flattens the results.

Parameters:

Name Type Description Default
mapper Callable[[T], Iterable[K]]

function (T) -> Iterable[K]

required

Returns: Lazy[K]

Examples:

>>> QList([1, 2]).flatmap(lambda x: [x, x]).qlist()
[1, 1, 2, 2]
Source code in src\qwlist\qwlist.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def flatmap(self, mapper: Callable[[T], Iterable[K]]) -> Lazy[K]:
    """
    Applies the mapper function to each element of the `QList` and flattens the results.

    Args:
        mapper: `function (T) -> Iterable[K]`

    Returns: `Lazy[K]`

    Examples:
        >>> QList([1, 2]).flatmap(lambda x: [x, x]).qlist()
        [1, 1, 2, 2]
    """
    def inner():
        for elem in self:
            yield from mapper(elem)
    return Lazy(inner())

flatten()

If self is a QList of Iterable[T] flatten concatenates all iterables into a single list and returns a Lazy[T] object Returns: Lazy[T]

Source code in src\qwlist\qwlist.py
516
517
518
519
520
521
522
523
524
525
def flatten(self) -> Lazy[T]:
    """
    If self is a QList of Iterable[T] flatten concatenates all iterables into a
    single list and returns a Lazy[T] object
    Returns: Lazy[T]
    """
    def inner():
        for elem in self:
            yield from elem
    return Lazy(inner())

fold(operation, init)

Given the combination operator reduces the QList by processing its values, building up the final value.

Other names: fold_left, reduce, accumulate, aggregate

Parameters:

Name Type Description Default
operation Callable[[K, T], K]

function: (K, T) -> K Given the initial value init applies the given combination operator on each element of the QList, treating the result as a first argument in the next step.

required
init K

initial value for the combination operator.

required

Returns: K

Examples:

>>> QList([1, 2, 3]).fold(lambda acc, x: acc + x, 0)
6
Source code in src\qwlist\qwlist.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def fold(self, operation: Callable[[K, T], K], init: K) -> K:
    """
    Given the combination operator reduces the `QList` by processing
    its values, building up the final value.

    **Other names:** fold_left, reduce, accumulate, aggregate

    Args:
        operation: `function: (K, T) -> K`
            Given the initial value `init` applies the
            given combination operator on each element of the `QList`,
            treating the result as a first argument in the next step.
        init: initial value for the combination operator.

    Returns: `K`

    Examples:
        >>> QList([1, 2, 3]).fold(lambda acc, x: acc + x, 0)
        6
    """
    acc = init
    for elem in self:
        acc = operation(acc, elem)
    return acc

fold_right(operation, init)

Given the combination operator reduces the QList by processing its values, building up the final value.

Parameters:

Name Type Description Default
operation Callable[[K, T], K]

function: (K, T) -> K Given the initial value init applies the given combination operator on each element of the QList, starting from the last element, treating the result as a first argument in the next step.

required
init K

initial value for the combination operator.

required

Returns: K

Examples:

>>> QList([1, 2, 3]).fold_right(lambda acc, x: acc + x, 0)
6
Source code in src\qwlist\qwlist.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def fold_right(self, operation: Callable[[K, T], K], init: K) -> K:
    """
    Given the combination operator reduces the `QList` by processing
    its values, building up the final value.

    Args:
        operation: `function: (K, T) -> K`
            Given the initial value `init` applies the
            given combination operator on each element of the `QList`, starting from the
            last element, treating the result as a first argument in the next step.
        init: initial value for the combination operator.

    Returns: `K`

    Examples:
        >>> QList([1, 2, 3]).fold_right(lambda acc, x: acc + x, 0)
        6
    """
    acc = init
    for elem in self[::-1]:
        acc = operation(acc, elem)
    return acc

foreach(action)

Applies the given function to each of the QList elements.

Parameters:

Name Type Description Default
action Callable[[T], None]

function (T) -> None

required

Returns: None

Source code in src\qwlist\qwlist.py
357
358
359
360
361
362
363
364
365
366
367
def foreach(self, action: Callable[[T], None]):
    """
    Applies the given function to each of the `QList` elements.

    Args:
        action: `function (T) -> None`

    Returns: `None`
    """
    for elem in self:
        action(elem)

len()

Returns the len of the QList

(time complexity: O(1))

Returns: int

Source code in src\qwlist\qwlist.py
417
418
419
420
421
422
423
424
425
def len(self) -> int:
    """
    Returns the len of the `QList`

    (time complexity: `O(1)`)

    Returns: int
    """
    return len(self)

list()

Changes QList into list.

Returns: list[T]

Source code in src\qwlist\qwlist.py
305
306
307
308
309
310
311
def list(self) -> list[T]:
    """
    Changes `QList` into `list`.

    Returns: `list[T]`
    """
    return list(self)

map(mapper)

Returns a Lazy object containing all values from QList with the mapping function applied on them.

Parameters:

Name Type Description Default
mapper Callable[[T], K]

function: (T) -> K

required

Returns: Lazy[K]

Source code in src\qwlist\qwlist.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def map(self, mapper: Callable[[T], K]) -> Lazy[K]:
    """
    Returns a `Lazy` object containing all values from `QList` with
    the mapping function applied on them.

    Args:
        mapper: `function: (T) -> K`

    Returns: `Lazy[K]`
    """
    def inner():
        for elem in self:
            yield mapper(elem)
    return Lazy(inner())

skip(n)

Skips n first elements of the QList.

Parameters:

Name Type Description Default
n int

numbers of elements to skip. Should be non-negative

required

Returns: Lazy[T]

Examples:

>>> QList(range(10)).skip(2).collect()
[2, 3, 4, 5, 6, 7, 8, 9]
Source code in src\qwlist\qwlist.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def skip(self, n: int) -> Lazy[T]:
    """
    Skips n first elements of the QList.

    Args:
        n: numbers of elements to skip. Should be non-negative

    Returns: Lazy[T]

    Examples:
        >>> QList(range(10)).skip(2).collect()
        [2, 3, 4, 5, 6, 7, 8, 9]
    """
    def inner():
        for i, elem in enumerate(self):
            if i >= n:
                yield elem
    return Lazy(inner())

slice(s)

Calling this method with s equal to slice(3) works similarly to list[:3] but is lazy evaluated.

Parameters:

Name Type Description Default
s slice

slice object

required

Returns: Lazy[T]

Source code in src\qwlist\qwlist.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def slice(self, s: slice) -> Lazy[T]:
    """
    Calling this method with `s` equal to `slice(3)` works similarly to
    `list[:3]` but is lazy evaluated.

    Args:
        s: slice object

    Returns: `Lazy[T]`
    """
    assert isinstance(s, slice), f"slice method argument must be a slice object. Got {type(s)}."

    def inner():
        for elem in self[s]:
            yield elem
    return Lazy(inner())

sorted(key=None, reverse=False)

Returns a new QList containing all items from the original list in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

Parameters:

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

function (T) -> SupportsLessThan. Defaults to None

None
reverse bool

if set to True sorts values in descending order. Defaults to False

False

Returns: QList[T]

Source code in src\qwlist\qwlist.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def sorted(self, key: Callable[[T], SupportsLessThan] = None, reverse: bool = False) -> "QList[T]":
    """
    Returns a new `QList` containing all items from the original list in ascending order.

    A custom key function can be supplied to customize the sort order, and the reverse
    flag can be set to request the result in descending order.

    Args:
        key: `function (T) -> SupportsLessThan`. Defaults to `None`
        reverse: if set to `True` sorts values in descending order. Defaults to `False`

    Returns: `QList[T]`
    """
    return QList(sorted(self, key=key, reverse=reverse))

take(n)

Takes n first elements of the QList.

Parameters:

Name Type Description Default
n int

int - numbers of elements to take. Should be non-negative

required

Returns: Lazy[T]

Examples:

>>> QList(range(10)).take(2).collect()
[0, 1]
Source code in src\qwlist\qwlist.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def take(self, n: int) -> Lazy[T]:
    """
    Takes n first elements of the QList.

    Args:
        n: int - numbers of elements to take. Should be non-negative

    Returns: Lazy[T]

    Examples:
        >>> QList(range(10)).take(2).collect()
        [0, 1]
    """
    def inner():
        for i, elem in enumerate(self):
            if i >= n:
                return None
            yield elem
    return Lazy(inner())

zip(other)

Combines this QList with the given Iterable elementwise as tuples. The returned Lazy objects yields at most the number of elements of the shorter sequence (self or Iterable).

Parameters:

Name Type Description Default
other Iterable[K]

iterable to zip with this QList.

required

Returns: Lazy[tuple[T, K]]

Examples:

>>> Lazy([1, 2, 3]).zip(['a', 'b', 'c']).collect()
[(1, 'a'), (2, 'b'), (3, 'c')]
Source code in src\qwlist\qwlist.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def zip(self, other: Iterable[K]) -> Lazy[tuple[T, K]]:
    """
    Combines this `QList` with the given `Iterable` elementwise as tuples.
     The returned `Lazy` objects yields at most the number of elements of
     the shorter sequence (`self` or `Iterable`).

    Args:
        other: iterable to zip with this `QList`.

    Returns: `Lazy[tuple[T, K]]`

    Examples:
        >>> Lazy([1, 2, 3]).zip(['a', 'b', 'c']).collect()
        [(1, 'a'), (2, 'b'), (3, 'c')]
    """
    return Lazy(zip(self, other))