Table of contents

Byte

The bytes data type is a built-in Python sequence type used to store a sequence of bytes, where each byte is an integer in the range of 0 to 255 (inclusive).

  • bytes is a pre-defined class treated as a sequence data type, similar to str or tuple.
  • It is used to represent binary data or sequences of single-byte integers.
  • Stores positive integer values from 0 to 255 (256 values, as 256 - 1 = 255).
  • Commonly used for handling binary data, such as file I/O, network protocols, or encoding/decoding.
  • Created using the bytes() constructor, which converts an iterable of integers (or other compatible objects) into a bytes object.
  • Syntax: varname = bytes(object)
t = (10, 20, 30, 255, 34, 0) print(t, type(t)) # (10, 20, 30, 255, 34, 0) <class 'tuple'> b = bytes(t) print(b, type(b)) # b'\n\x14\x1e\xff"\x00' <class 'bytes'>
  • The input must contain integers in the range 0 to 255; otherwise, a ValueError is raised.
  • Non-integer elements (e.g., strings) cause a TypeError.
  • Supports indexing (e.g., b[0]) and slicing (e.g., b[2:5]), returning individual bytes or a new bytes object.
t = (10, 20, 30, 255, 34, 0) print(t, type(t)) # (10, 20, 30, 255, 34, 0) <class 'tuple'> b = bytes(t) print(b, type(b)) # b'\n\x14\x1e\xff"\x00' <class 'bytes'> # Iteration for v in b: print(v) # 10, 20, 30, 255, 34, 0 # Indexing print(b[0]) # 10 print(b[-1]) # 0 print(b[-2]) # 34 # Slicing print(b[2:5]) # b'\x1e\xff"' for v in b[2:5]: print(v) # 30, 255, 34
  • Maintains insertion order, meaning the order of elements in the input iterable is preserved in the bytes object.
  • bytes objects are immutable, like str and tuple.
  • Item assignment (e.g., b[0] = 100) raises TypeError.
  • nlike lists ([]) or tuples (()), bytes has no literal syntax for direct creation.
  • Must use bytes() or b'' (bytes literal for ASCII or escape sequences).
l = [10, 20, 30, 0, 34, 56, 78, 255] print(l, type(l)) # [10, 20, 30, 0, 34, 56, 78, 255] <class 'list'> b = bytes(l) print(b, type(b), id(b)) # b'\n\x14\x1e\x00"8N\xff' <class 'bytes'> <id> # Indexing print(b[0]) # 10 print(b[-1]) # 255 # Iteration for k in b: print(k) # 10, 20, 30, 0, 34, 56, 78, 255 # Reverse iteration for k in b[::-1]: print(k) # 255, 78, 56, 34, 0, 30, 20, 10 # Step slicing for k in b[::2]: print(k) # 10, 30, 34, 78 for k in b[::-2]: print(k) # 255, 56, 0, 20 # Immutability try: b[0] = 200 except TypeError as e: print("Error:", e) # Error: 'bytes' object does not support item assignment