bytearray.extend()
The bulk form of append. Unlike append it DOES accept a bytes object, because bytes is itself an iterable of ints — an inconsistency worth remembering.
Demo
Every value in the iterable is appended in order, so 100 and 101 add the letters d and e. An empty iterable is a harmless no-op rather than an error. As with append, each value must fit in a byte — and one out-of-range number rejects the ENTIRE call, leaving the buffer untouched rather than partially extended.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| iterable | iterable | yes | Any iterable of ints in 0 to 255 — a list, a range, another bytes or bytearray. A str raises TypeError. |
Return value
None — Returns None — the buffer grows in place. The demo wraps the call so the resulting buffer is visible.
Common patterns
buf = bytearray() while chunk := sock.recv(4096): buf.extend(chunk)
buf.extend(header)
buf.extend('héllo'.encode('utf-8'))
Examples
Pitfalls
buf.extend('ab')
buf.extend('ab'.encode('utf-8'))
buf = bytearray() buf.extend([1, 2, 256]) # ValueError buf
buf.extend(v & 0xFF for v in values)
buf.extend(100)
buf.append(100)
buf = buf.extend(chunk)
buf.extend(chunk)
When to use
- Accumulating chunks read from a socket or file
- Appending another bytes or bytearray
- Adding several byte values at once
- A single byte → append is clearer
- Adding at a position → insert
- The result never changes → build bytes with join instead
Notes
FAQ
Because bytes IS an iterable of ints — iterating it yields values from 0 to 255, exactly what extend wants. append needs a single int, and a bytes object is not one, even when it holds only one byte.
buf.extend(b'cd') # fine buf.append(b'd') # TypeError