Binary Types:
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!1.) bytes:
- 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'>2.) bytearray:
- 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')3.) memoryview:
- 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')None Type in Python:
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