Range, Bytes and Bytearray

Python Range

The range() function is like a counting machine. Instead of writing out every number manually, you tell Python where to start, where to stop, and how many steps to skip. It is most commonly used in loops to repeat an action a specific number of times without taking up much memory.

  • Memory Efficient: It doesn’t actually “store” all the numbers; it just remembers the rules (start, stop, step) and generates the next number only when you need it.
  • The “Stop” Rule: Just like slicing, the “stop” number is never included in the result. If you say range(1, 5), it counts 1, 2, 3, 4.
# Counting from 0 to 4
for i in range(5):
    print(i)  #output: 0, 1, 2, 3, 4

# Counting from 10 to 20, jumping by 2
numbers = list(range(10, 21, 2))
print(numbers)  # Output: [10, 12, 14, 16, 18, 20]

Python Bytes

The bytes data type is used to handle binary data. This is the “raw” language of computers, representing things like images, music files, or network packets. Each item in a bytes object must be an integer between 0 and 255.
  • Immutable (Unchangeable): Once you create a bytes object, you cannot modify its content. It is a “read-only” version of binary data.
  • Usage: You will mostly see this when reading files in “rb” (read binary) mode or when sending data over the internet.
# Creating bytes from a list
numbers = [65, 66, 67]
b = bytes(numbers)
print(b) # Output: b'ABC' (65 is the code for 'A')
# b[0] = 68  <-- This would cause an ERROR

Python Bytearray

A bytearray is the “flexible” version of bytes. It still stores raw binary data (integers from 0 to 255), but unlike the standard bytes type, it is mutable. This means you can change, add, or delete parts of the data after it has been created.
  • Digital Sketchpad: Think of bytes as a printed photograph and bytearray as a digital image in an editor—you can swap out pixels (bytes) as much as you like.
  • Performance: It is very efficient for programs that need to modify large amounts of binary data frequently, such as image processing or data encryption tools.
# Creating a bytearray
ba = bytearray([65, 66, 67])

# Changing the first element (65 to 90)
ba[0] = 90
print(ba) # Output: bytearray(b'ZBC')

Quick Comparison Table

Featurerangebytesbytearray
Data TypeNumbers/SequencesBinary (0-255)Binary (0-255)
Changeable?NoNo (Immutable)Yes (Mutable)
Primary UseCounting in loopsStoring raw dataEditing raw data
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top