Skip to content

Inconsistent .extend() behavior in bytearray #145300

@tim-one

Description

@tim-one

Bug report

Bug description:

Extending a bytearrary can behave very differently when extending via an iterable than when extending a list or array.array in the same way:

>>> from itertools import islice
>>> xs = [0, 1, 2]
>>> xs.extend(islice(xs, 12000))
>>> len(xs)
12003
>>> import array
>>> xs = array.array('Q', [0, 1, 2])
>>> xs.extend(islice(xs, 12000))
>>> len(xs)
12003

Tricky, but it's always worked this way, and is very convenient to extend a sequence with copies of itself. Note that the iterator picks up new elements of the sequence while they're being added.

bytearray doesn't work this way, though. It appears to capture the sequence's length just once at the start, and so can't do more than double the original length.

>>> xs = bytearray([0, 1, 2])
>>> xs.extend(islice(xs, 12000))
>>> len(xs)
6
>>> list(xs)
[0, 1, 2, 0, 1, 2]

Bumped into this when changing old code to switch from lists of small ints to bytearrays instead. Quite a head-scratcher to figure out what went wrong! ;-)

CPython versions tested on:

3.15, 3.14

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions