Mathew K Analytics

Lesson 12 · Python data types deep dive

Python Bytearrays Explained: Mutable Binary Data | Data Types #12

Video twelve, the final video of the twelve-part series: bytearray, bytes' mutable sibling. Every one of bytes' forty-two methods still applies, plus eight…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Data Types Deep-Dive, Video 12: Bytearrays (bytearray)#

  • Video twelve, the final video of the twelve-part series: bytearray, bytes' mutable sibling.
  • Every one of bytes' forty-two methods still applies, plus eight new ones for genuine in-place mutation, for all fifty public methods total.
  • Let's finish the series.

Part 1: What Makes bytearray Different#

data = bytearray(b'hello')
print(type(data))
print(len(data))
data[0] = 72
print(data)
print(bytes(data))
<class 'bytearray'>
5
bytearray(b'Hello')
b'Hello'

Part 2: Construction#

empty = bytearray()
from_bytes = bytearray(b'hello')
from_ints = bytearray([72, 101, 108, 108, 111])
zero_filled = bytearray(5)
from_string = bytearray('hello', encoding='utf-8')
from_hex = bytearray.fromhex('48656c6c6f')
print(empty, from_bytes, from_ints, zero_filled, from_string, from_hex)
bytearray(b'') bytearray(b'hello') bytearray(b'Hello') bytearray(b'\x00\x00\x00\x00\x00') bytearray(b'hello') bytearray(b'Hello')

Part 3: Indexing, Slicing, and Assignment#

data = bytearray(b'python')
print(data[0])
print(data[1:4])
data[0] = ord('P')
print(data)
data[1:4] = b'YTH'
print(data)
data[0:2] = b'XX'
print(data)
112
bytearray(b'yth')
bytearray(b'Python')
bytearray(b'PYTHon')
bytearray(b'XXTHon')

Part 4: Adding Elements: append(), extend(), insert()#

buf = bytearray(b'hello')
buf.append(33)
print(buf)
buf.extend(b' world')
print(buf)
buf.insert(0, ord('>'))
print(buf)
bytearray(b'hello!')
bytearray(b'hello! world')
bytearray(b'>hello! world')

Part 5: Removing Elements: remove(), pop(), clear()#

buf = bytearray(b'hello!')
buf.remove(ord('!'))
print(buf)
last = buf.pop()
print(last, buf)
buf.clear()
print(buf)
bytearray(b'hello')
111 bytearray(b'hell')
bytearray(b'')

Part 6: reverse()#

buf = bytearray(b'hello')
result = buf.reverse()
print(buf)
print(result)
buf2 = bytearray(b'hello')
print(buf2[::-1])
bytearray(b'olleh')
None
bytearray(b'olleh')

Part 7: copy()#

original = bytearray(b'data')
alias = original
alias.append(33)
print(original)
real_copy = original.copy()
real_copy.append(63)
print(original)
print(real_copy)
bytearray(b'data!')
bytearray(b'data!')
bytearray(b'data!?')

Part 8: decode(), hex(), and fromhex()#

buf = bytearray('caf'.encode('utf-8'))
print(buf.decode('utf-8'))
print(buf.hex())
print(buf.hex(' '))
restored = bytearray.fromhex(buf.hex())
print(restored == buf)
caf
636166
63 61 66
True

Part 9: Case-Changing Methods#

text = bytearray(b'the Quick BROWN fox')
print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())
print(text)
bytearray(b'THE QUICK BROWN FOX')
bytearray(b'the quick brown fox')
bytearray(b'The quick brown fox')
bytearray(b'The Quick Brown Fox')
bytearray(b'THE qUICK brown FOX')
bytearray(b'the Quick BROWN fox')

Part 10: Case-Checking Methods#

print(bytearray(b'HELLO').isupper())
print(bytearray(b'Hello').isupper())
print(bytearray(b'hello').islower())
print(bytearray(b'Hello World').istitle())
True
False
True
True

Part 11: Padding: center, ljust, rjust, zfill#

word = bytearray(b'hi')
print(word.center(10, b'*'))
print(word.ljust(10, b'.'))
print(word.rjust(10, b'.'))
print(bytearray(b'42').zfill(5))
bytearray(b'****hi****')
bytearray(b'hi........')
bytearray(b'........hi')
bytearray(b'00042')

Part 12: Stripping: strip, lstrip, rstrip#

messy = bytearray(b'   padded   ')
print(messy.strip())
print(messy.lstrip())
print(messy.rstrip())
print(bytearray(b'xxhelloxx').strip(b'x'))
bytearray(b'padded')
bytearray(b'padded   ')
bytearray(b'   padded')
bytearray(b'hello')

Part 13: Searching: find, rfind, index, rindex, count, startswith, endswith#

data = bytearray(b'the quick brown fox')
print(data.find(b'quick'))
print(data.find(b'slow'))
print(data.rfind(b'o'))
print(data.index(b'brown'))
print(data.count(b'o'))
print(data.startswith(b'the'))
print(data.endswith(b'fox'))
4
-1
17
10
2
True
True

Part 14: split, rsplit, splitlines, partition, rpartition, join, replace#

row = bytearray(b'apple,banana,cherry')
print(row.split(b','))
print(row.rsplit(b',', 1))
print(row.partition(b','))
print(row.rpartition(b','))
print(bytearray(b'a\nb\nc').splitlines())
[bytearray(b'apple'), bytearray(b'banana'), bytearray(b'cherry')]
[bytearray(b'apple,banana'), bytearray(b'cherry')]
(bytearray(b'apple'), bytearray(b','), bytearray(b'banana,cherry'))
(bytearray(b'apple,banana'), bytearray(b','), bytearray(b'cherry'))
[bytearray(b'a'), bytearray(b'b'), bytearray(b'c')]
parts = [bytearray(b'the'), bytearray(b'fox')]
print(bytearray(b' ').join(parts))
text = bytearray(b'the cat sat')
print(text.replace(b'cat', b'dog'))
print(text)
bytearray(b'the fox')
bytearray(b'the dog sat')
bytearray(b'the cat sat')

Part 15: Character Classification Methods#

print(bytearray(b'Python3').isalnum())
print(bytearray(b'Python').isalpha())
print(bytearray(b'123').isdigit())
print(bytearray(b'   ').isspace())
print(bytearray(b'hello').isascii())
True
True
True
True
True

Part 16: translate, maketrans, expandtabs, removeprefix, removesuffix#

table = bytearray.maketrans(b'aeiou', b'AEIOU')
print(bytearray(b'the quick fox').translate(table))
print(bytearray(b'name\tage').expandtabs(4))
filename = bytearray(b'IMG_001.png')
print(filename.removeprefix(b'IMG_'))
print(filename.removesuffix(b'.png'))
bytearray(b'thE qUIck fOx')
bytearray(b'name    age')
bytearray(b'001.png')
bytearray(b'IMG_001')

Part 17: In-Place Binary Manipulation Patterns#

buffer = bytearray(4)
print(buffer)
import struct
struct.pack_into('>I', buffer, 0, 1024)
print(buffer)
print(buffer.hex())
bytearray(b'\x00\x00\x00\x00')
bytearray(b'\x00\x00\x04\x00')
00000400
growing_buffer = bytearray()
for chunk in [b'header:', b'12345', b';body:', b'payload data']:
    growing_buffer.extend(chunk)
print(growing_buffer)
print(bytes(growing_buffer))
with open('buffer_demo.bin', 'wb') as f:
    f.write(growing_buffer)
bytearray(b'header:12345;body:payload data')
b'header:12345;body:payload data'

Wrap-Up: What You Learned#

  • bytearray is bytes' mutable sibling: same value range per byte, but resizable and editable in place.
  • Construction, indexing, slicing, and both single-index and slice assignment.
  • Eight mutable-only methods: append, extend, insert, remove, pop, clear, reverse, copy.
  • All forty-two bytes methods carry over identically: decode, hex, fromhex, case methods, padding, stripping, searching, splitting, joining, replacing, classification, translate, expandtabs, removeprefix, removesuffix.
  • Real in-place binary patterns: pre-allocated buffers, struct.pack_into, and efficient buffer building with extend.
  • That's all fifty public bytearray methods covered, and the twelfth and final video in the Python Data Types Deep-Dive series.
  • Thanks for following along through every single built-in type. See you in the next series.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.