bytearray.pop()
The only bytearray mutator whose return value matters. It hands back an INT, not a one-byte bytes object.
Demo
The demo shows what pop RETURNS — an integer, not bytes. Popping from "abc" gives 99, the ASCII code for c, and the buffer would be left holding just ab. The digits case is the usual trip-up: popping from "123" gives 51, the code for the character three, not the number three. An empty buffer raises IndexError, and unlike dict.pop there is no default argument to soften it.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| index | int | no (-1) | Position to remove. Defaults to the last byte. Negative counts from the end. Out of range raises IndexError. |
Return value
int — The removed byte as an integer from 0 to 255. Raises IndexError on an empty buffer.
Common patterns
buf.append(value) ... value = buf.pop()
if buf and buf[-1] == 0x0a: buf.pop()
while buf: handle(buf.pop())
Examples
Pitfalls
bytearray(b'abc').pop() == b'c'
bytearray(b'abc').pop() == ord('c')
while True: handle(buf.pop())
while buf: handle(buf.pop())
while buf: handle(buf.pop(0))
from collections import deque q = deque(buf) q.popleft()
bytearray(b'123').pop()
int(bytes(bytearray(b'123')))
When to use
- Treating a buffer as a byte stack
- Removing and inspecting a trailing byte in one step
- Draining a buffer from the end
- FIFO order → collections.deque
- You only want to look → index with buf[-1]
- Removing by VALUE rather than position → remove
Notes
FAQ
Because a bytearray is a sequence of integers — indexing gives an int, and so does popping. Only slicing produces a bytes object, which is the asymmetry behind most bytearray confusion.
b = bytearray(b'abc') b[-1] # 99 b[-1:] # bytearray(b'c')