Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. Binary Types and None Type in Python

Binary Types and None Type in Python

Python provides three built-in binary types for working with binary data. These types are useful for tasks involving files, network communication, and memory-level operations.

Thank you for reading this post, don't forget to subscribe!
  • bytes is an immutable sequence of binary data (0s and 1s).
  • It is defined by prefixing a string with a lowercase b, like b’hello’.

Example:

data = b'hello'
print(data)         # Output: b'hello'
print(type(data))   # Output: <class 'bytes'>
  • bytearray is a mutable sequence of binary data.
  • Unlike bytes, you can change elements in a bytearray.

    Example:

    arr = bytearray(b'hello')
    arr[0] = 72        # ASCII of 'H'
    print(arr)         # Output: bytearray(b'Hello')
    • memoryview allows memory-level access to binary data without copying it.
    • It is mainly used for performance optimization in large data operations.

    Example:

    data = bytearray(b'abc')
    mv = memoryview(data)
    print(mv[0])       # Output: 97 (ASCII of 'a')

    The None type in Python represents the absence of a value, similar to null in other languages.

    • It is used when a variable is declared but has no value assigned yet, or a function does not return anything explicitly.

    Example:

    x = None
    print(x)            # Output: None
    print(type(x))      # Output: <class 'NoneType'>

    Another example (function with no return):

    def greet():
        print("Hello!")
    
    result = greet()
    print(result)       # Output: None

    How can we help?