bytearray.append()
Takes a single INT, not a bytes object. That asymmetry — bytearray indexes to ints but slices to bytes — is the thing to internalise about this type.
Demo
The demo expression looks odd because append returns None — the walrus and the list index exist purely so you can see the resulting buffer instead. Appending 100 adds the letter d, because 100 is its ASCII code. Values outside 0 to 255 raise ValueError, since a byte cannot hold them. Note that non-printable bytes such as 10 and 0 appear as escapes in the output rather than as characters.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| byte | int | yes | An integer from 0 to 255. Anything outside that range raises ValueError; a bytes object 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() for value in values: buf.append(value)
buf.append(0x0a) # newline
return bytes(buf)
Examples
Pitfalls
buf.append(b'd')
buf.append(ord('d')) # or 100
buf.append(300)
buf.append(300 & 0xFF)
buf.append([1, 2])
buf.extend([1, 2])
buf = buf.append(100)
buf.append(100)
When to use
- Building a binary buffer incrementally
- Adding a single delimiter or terminator byte
- Any loop where bytes concatenation would copy repeatedly
- Adding several bytes → extend
- Adding at a position → insert
- The buffer never changes → build bytes directly
Notes
FAQ
Because a bytearray is a sequence of INTEGERS. Indexing one gives an int, and appending one takes an int. The confusion comes from slicing, which gives bytes back — the two operations genuinely differ.
b = bytearray(b'abc') b[0] # 97, an int b[0:1] # b'a', a bytes object