<< Back to PYTHON
Python bytes, bytearray Examples (memoryview)
Use the bytes, bytearray and memoryview types. Represent data in an efficient way.Byte. The universe is composed of units (indivisible units) like atoms (or bytes). With bytes, we have an addressable unit of memory. Python can act upon bytes.
In this language, we use the bytes and bytearray built-ins. These objects interact directly with byte data. A byte can store 0 through 255.
Bytearray example. This example creates a list. Each number in the list is between 0 and 255 (inclusive). We create a bytearray from the list.
Modify: We modify the first 2 elements in the bytearray. This cannot be done with a bytes object.
For: We use the for-loop to iterate over the bytearray's elements. This is the same as how we use a list.
forPython program that creates bytearray from list
elements = [0, 200, 50, 25, 10, 255]
# Create bytearray from list of integers.
values = bytearray(elements)
# Modify elements in the bytearray.
values[0] = 5
values[1] = 0
# Display bytes.
for value in values:
print(value)
Output
5
0
50
25
10
255
Bytes example. We now consider "bytes." This is similar to bytearray. But the elements of a bytes object cannot be changed. It is an immutable array of bytes.
Buffer protocol: Bytearray, bytes and memoryview act upon the buffer protocol. They all share similar syntax with small differences.
Python program that creates bytes object
elements = [5, 10, 0, 0, 100]
# Create immutable bytes object.
data = bytes(elements)
# Loop over bytes.
for d in data:
print(d)
Output
5
10
0
0
100
Error. Now we get into some trouble—that is always fun. Here we try to modify the first element of a bytes object. Python complains—the "object does not support item assignment."
Python program that causes error
data = bytes([10, 20, 30, 40])
# We can read values from a bytes object.
print(data[0])
# We cannot assign elements.
data[0] = 1
Output
10
Traceback (most recent call last):
File "/Users/sam/Documents/test.py", line 9, in <module>
data[0] = 1
TypeError: 'bytes' object does not support item assignment
Len. We can get the length of a bytearray or bytes object with the len built-in. Here we use bytearray in the same way as a string or a list.
LenPython program that uses len, gets byte count
# Create bytearray from some data.
values = bytearray([6, 7, 60, 70, 0])
# It has 5 elements.
# ... The len is 5.
print("Element count:", len(values))
Output
Element count: 5
Literals. Bytes and bytearray objects can be created with a special string literal syntax. We prefix the literals with a "b." This prefix is required.
Tip: Buffer protocol methods require byte-prefix string literals, even for arguments to methods like replace().
Python program that uses byte literals
# Create bytes object from byte literal.
data = bytes(b"abc")
for value in data:
print(value)
print()
# Create bytearray from byte literal.
arr = bytearray(b"abc")
for value in arr:
print(value)
Output
97
98
99
97
98
99
Slice, bytearray. We can slice bytearrays. And because bytearray is mutable, we can use slices to change its contents. Here we assign a slice to an integer list.
Python program that uses slice, changes bytearray
values = [5, 10, 15, 20]
arr = bytearray(values)
# Assign first two elements to new list.
arr[0:2] = [100, 0, 0]
# The array is now modified.
for v in arr: print(v)
Output
100
0
0
15
20
Slice, bytes. A bytes object too supports slice syntax, but it is read-only. Here we get a slice of bytes (the first two elements) and loop over it.
Often: We can loop over a slice directly in the for-loop condition. The variable is not needed.
Python program that uses slice, bytes
data = bytes(b"abc")
# Get a slice from the bytes object.
first_part = data[0:2]
# Display values from slice.
for element in first_part: print(element)
Output
97
98
Count. Many methods are available on the buffer interface. Count is one. It loops through the bytes and counts instances matching our specified pattern.
Note: Count must loop through all elements. If another loop is needed afterwards, often we can combine loops for speed.
Argument: The argument to count() must be a byte object, like a "b" string literal or a number between 0 and 255.
Python program that uses count, buffer interface
# Create a bytes object and a bytearray.
data = bytes(b"aabbcccc")
arr = bytearray(b"aabbcccc")
# The count method (from the buffer interface) works on both.
print(data.count(b"c"))
print(arr.count(b"c"))
Output
4
4
Find. This method returns the leftmost index of a matching sequence. Optionally we can specify a start index and an end index (as the second and third arguments).
Python program that uses find
data = bytes(b"python")
# This sequence is found.
index1 = data.find(b"on")
print(index1)
# This sequence is not present.
index2 = data.find(b"java")
print(index2)
Output
4
-1
In operator. This tests for existence. We use "in" to see if an element exists within the bytes objects. This is a clearer way to see if a byte exists in our object.
Python program that uses in operator
data = bytes([100, 20, 10, 200, 200])
# Test bytes object with "in" operator.
if 200 in data:
print(True)
if 0 not in data:
print(False)
Output
True
False
Combine two bytearrays. As with lists and other sequences, we can combine two bytearrays (or bytes) with a plus. In my tests, I found it does not matter if we combine two different types.
Python program that uses plus on bytearrays
left = bytearray(b"hello ")
right = bytearray(b"world")
# Combine two bytearray objects with plus.
both = left + right
print(both)
Output
bytearray(b'hello world')
Convert list. A list of bytes (numbers between 0 and 256) can be converted into a bytearray with the constructor. To convert back into a list, please use the list built-in constructor.
Tip: Lists display in a more friendly way with the print method. So we might use this code to display bytearrays and bytes.
Python program that uses list built-in
initial = [100, 255, 255, 0]
print(initial)
# Convert the list to a byte array.
b = bytearray(initial)
print(b)
# Convert back to a list.
result = list(b)
print(result)
Output
[100, 255, 255, 0]
bytearray(b'd\xff\xff\x00')
[100, 255, 255, 0]
Convert string. A bytearray can be created from a string. The encoding (like "ascii") is specified as the second argument in the bytearray constructor.
Decode: To convert from a bytearray back into a string, the decode method is needed.
Python program that converts string, bytearray
# Create a bytearray from a string with ASCII encoding.
arr = bytearray("abc", "ascii")
print(arr)
# Convert bytearray back into a string.
result = arr.decode("ascii")
print(result)
Output
bytearray(b'abc')
abc
Append, del, insert. A bytearray supports many of the same operations as a list. We can append values. We can delete a value or a range of values with del. And we can insert a value.
Python program that uses append, del, insert
# Create bytearray and append integers as bytes.
values = bytearray()
values.append(0)
values.append(1)
values.append(2)
print(values)
# Delete the first element.
del values[0:1]
print(values)
# Insert at index 1 the value 3.
values.insert(1, 3)
print(values)
Output
bytearray(b'\x00\x01\x02')
bytearray(b'\x01\x02')
bytearray(b'\x01\x03\x02')
ValueError. Numbers inserted into a bytearray or bytes object must be between 0 and 255 inclusive. If we try to insert an out-of-range number, we will receive a ValueError.
Python program that causes ValueError
# This does not work.
values = bytes([3000, 4000, 5000])
print("Not reached")
Output
Traceback (most recent call last):
File "/Users/sam/Documents/test.py", line 4, in <module>
values = bytes([3000, 4000, 5000])
ValueError: byte must be in range(0, 256)
Replace. The buffer protocol supports string-like methods. We can use replace() as on a string. The arguments must be bytes objects—here we use "b" literals.
Python program that uses replace on bytes
value = b"aaabbb"
# Use bytes replace method.
result = value.replace(b"bbb", b"ccc")
print(result)
Output
b'aaaccc'
Compare. A "b" literal is a bytes object. We can compare a bytearray or a bytes object with this kind of constant. To compare bytes objects, we use two equals signs.
Note: Two equals signs compares the individual byte contents, not the identity of the objects.
Python program that compares bytes
# Create a bytes object with no "bytes" keyword.
value1 = b"desktop"
print(value1)
# Use bytes keyword.
value2 = bytes(b"desktop")
print(value2)
# Compare two bytes objects.
if value1 == value2:
print(True)
Output
b'desktop'
b'desktop'
True
Start, end. We can handle bytes objects much like strings. Common methods like startswith and endswith are included. These check the beginning and end parts.
Argument: The argument to startswith and endswith must be a bytes object. We can use the handy "b" prefix.
Python program that uses startswith, endswith
value = b"users"
# Compare bytes with startswith and endswith.
if value.startswith(b"use"):
print(True)
if value.endswith(b"s"):
print(True)
Output
True
True
Split, join. The split and join methods are implemented on bytes objects. Here we handle a simple CSV string in bytes. We separate values based on a comma char.
Python program that uses split, join
# A bytes object with comma-separate values.
data = b"cat,dog,fish,bird,true"
# Split on comma-byte.
elements = data.split(b",")
# Print length and list contents.
print(len(elements))
print(elements)
# Combine bytes objects into a single bytes object.
result = b",".join(elements)
print(result)
Output
5
[b'cat', b'dog', b'fish', b'bird', b'true']
b'cat,dog,fish,bird,true'
Memoryview. This is an abstraction that provides buffer interface methods. We can create a memoryview from a bytes object, a bytearray or another type like an array.
ArrayTip: With memoryview we can separate our code that uses the buffer interface from the actual data type. It is an abstraction.
Python program that uses memoryview
view = memoryview(b"abc")
# Print the first element.
print(view[0])
# Print the element count.
print(len(view))
# Convert to a list.
print(view.tolist())
Output
b'a'
3
[97, 98, 99]
Benchmark, bytearray. Suppose we want to append 256 values to a list. Bytearray is more complex to handle, and it does not support large numeric values. But it may help performance.
Version 1: This version of the code appends integers to a list collection in a nested loop.
Version 2: In this code, we append integers to a bytearray in a nested loop. The same values are used as in version 1.
Result: Bytearray here is faster. So we both improve memory size and reduce time required with bytearray over list.
Python program that times list, bytearray appends
import time
print(time.time())
# Version 1: append to list.
for i in range(0, 1000000):
x = list()
for v in range(0, 255):
x.append(v)
print(time.time())
# Version 2: append to bytearray.
for i in range(0, 1000000):
x = bytearray()
for v in range(0, 255):
x.append(v)
print(time.time())
Output
1411859925.29213
1411859927.673053 list append: 2.38 s
1411859929.463818 bytearray append: 1.79 s [faster]
Read bytes from file. A file can be read into a bytes object. We must specify the "b" mode—to read a file as bytes, we use the argument "rb."
File: Read Binary File
Bytes and bytearrays are an efficient, byte-based form of strings. They have many of the same methods as strings, but can also be used as lists.
Built-ins
In Python, lists can become inefficient quickly. And strings, immutable, lead to excessive copying. Where we represent data in bytes, numbers from 0 to 255, these buffer types are ideal.
Related Links:
- Python global and nonlocal
- Python not: If Not True
- Python Convert Decimal Binary Octal and Hexadecimal
- Python Tkinter Scale
- Python Tkinter Scrollbar
- Python Tkinter Text
- Python History
- Python Number: random, float and divmod
- Python Tkinter Toplevel
- Python Tkinter Spinbox
- Python Tkinter PanedWindow
- Python Tkinter LabelFrame
- Python Tkinter MessageBox
- Python Website Blocker
- Python Console Programs: Input and Print
- Python Display Calendar
- Python Check Number Odd or Even
- Python readline Example: Read Next Line
- Python Anagram Find Method
- Python Any: Any Versus All, List Performance
- Python Filename With Date Example (date.today)
- Python Find String: index and count
- Python filter (Lambda Removes From List or Range)
- Python ASCII Value of Character
- Python Sum Example
- Python make simple Calculator
- Python Add Two Matrices
- Python Multiply Two Matrices
- Python SyntaxError (invalid syntax)
- Python Transpose Matrix
- Python Remove Punctuation from String
- Python Dictionary items() method with Examples
- Python Dictionary keys() method with Examples
- Python Textwrap Wrap Example
- Python Dictionary popitem() method with Examples
- Python Dictionary pop() method with Examples
- Python HTML: HTMLParser, Read Markup
- Python Tkinter Tutorial
- Python Array Examples
- Python ord, chr Built Ins
- Python Dictionary setdefault() method with Examples
- Python Dictionary update() method with Examples
- Python Dictionary values() method with Examples
- Python complex() function with Examples
- Python delattr() function with Examples
- Python dir() function with Examples
- Python divmod() function with Examples
- Python Loops
- Python for loop
- Python while loop
- Python enumerate() function with Examples
- Python break
- Python continue
- Python dict() function with Examples
- Python pass
- Python Strings
- Python Lists
- Python Tuples
- Python Sets
- Python Built-in Functions
- Python filter() function with Examples
- Python dict Keyword (Copy Dictionary)
- Python Dictionary Order Benchmark
- Python Dictionary String Key Performance
- Python 2D Array: Create 2D Array of Integers
- Python Divmod Examples, Modulo Operator
- bin() in Python | Python bin() Function with Examples
- Python Oops Concept
- Python Object Classes
- Python Constructors
- Python hash() function with Examples
- Python Pandas | Python Pandas Tutorial
- Python Class Examples: Init and Self
- Python help() function with Examples
- Python IndentationError (unexpected indent)
- Python Index and Count (Search List)
- Python min() function with Examples
- Python classmethod and staticmethod Use
- Python set() function with Examples
- Python hex() function with Examples
- Python id() function with Examples
- Python sorted() function with Examples
- Python next() function with Examples
- Python Compound Interest
- Python List insert() method with Examples
- Python Datetime Methods: Date, Timedelta
- Python setattr() function with Examples
- Python 2D List Examples
- Python Pandas Data operations
- Python Def Methods and Arguments (callable)
- Python slice() function with Examples
- Python Remove HTML Tags
- Python input() function with Examples
- Python enumerate (For Index, Element)
- Python Display the multiplication Table
- Python int() function with Examples
- Python Error: Try, Except and Raise
- Python isinstance() function with Examples
- Python oct() function with Examples
- Python startswith, endswith Examples
- Python List append() method with Examples
- Python NumPy Examples (array, random, arange)
- Python Replace Example
- Python List clear() method with Examples
- Python List copy() method with Examples
- Python Lower Dictionary: String Performance
- Python Lower and Upper: Capitalize String
- Python Dictionary Examples
- Python map Examples
- Python Len (String Length)
- Python Padding Examples: ljust, rjust
- Python Type: setattr and getattr Examples
- Python String List Examples
- Python String
- Python Remove Duplicates From List
- Python If Examples: Elif, Else
- Python Programs | Python Programming Examples
- Python List count() method with Examples
- Python List extend() method with Examples
- Python List index() method with Examples
- Python List pop() method with Examples
- Python Palindrome Method: Detect Words, Sentences
- Python Path: os.path Examples
- Python List remove() method with Examples
- Python List reverse() method with Examples
- Top 50+ Python Interview Questions (2021)
- Python List sort() method with Examples
- Python sort word in Alphabetic Order
- abs() in Python | Python abs() Function with Examples
- Python String | encode() method with Examples
- all() in Python | Python all() Function with Examples
- any() in Python | Python any() Function with Examples
- Python Built In Functions
- ascii() in Python | Python ascii() Function with Examples
- Python bytes, bytearray Examples (memoryview)
- bool() in Python | Python bool() Function with Examples
- bytearray() in Python | Python bytearray() Function with Examples
- Python Caesar Cipher
- bytes() in Python | Python bytes() Function with Examples
- Python Sum of Natural Numbers
- callable() in Python | Python callable() Function with Examples
- Python Set add() method with Examples
- Python Set discard() method with Examples
- Python Set pop() method with Examples
- Python math.floor, import math Examples
- Python Return Keyword (Return Multiple Values)
- Python while Loop Examples
- Python Math Examples
- Python Reverse String
- Python max, min Examples
- Python pass Statement
- Python Set remove() method with Examples
- Python Dictionary
- Python Functions
- Python String | capitalize() method with Examples
- Python String | casefold() method with Examples
- Python re.sub, subn Methods
- Python subprocess Examples: subprocess.run
- Python Tkinter Checkbutton
- Python Tkinter Entry
- Python String | center() method with Examples
- Python Substring Examples
- Python pow Example, Power Operator
- Python Lambda
- Python Files I/O
- Python Modules
- Python String | count() method with Examples
- Python String | endswith() method with Examples
- Python String | expandtabs() method with Examples
- Python Prime Number Method
- Python String | find() method with Examples
- Python String | format() method with Examples
- Python String | index() method with Examples
- Python String | isalnum() method with Examples
- Python String | isalpha() method with Examples
- Python String | isdecimal() method with Examples
- Python Pandas Sorting
- Python String | isdigit() method with Examples
- Python Convert Types
- Python String | isidentifier() method with Examples
- Python Pandas Add column to DataFrame columns
- Python String | islower() method with Examples
- Python Pandas Reading Files
- Python Right String Part
- Python IOError Fix, os.path.exists
- Python Punctuation and Whitespace (string.punctuation)
- Python isalnum: String Is Alphanumeric
- Python Pandas Series
- Python Pandas DataFrame
- Python Recursion Example
- Python ROT13 Method
- Python StringIO Examples and Benchmark
- Python Import Syntax Examples: Modules, NameError
- Python in Keyword
- Python iter Example: next
- Python Round Up and Down (Math Round)
- Python List Comprehension
- Python Collection Module
- Python Math Module
- Python OS Module
- Python Random Module
- Python Statistics Module
- Python String Equals: casefold
- Python Sys Module
- Top 10 Python IDEs | Python IDEs
- Python Arrays
- Python Magic Method
- Python Stack and Queue
- Python MySQL Environment Setup
- Python MySQL Database Connection
- Python MySQL Creating New Database
- Python MySQL Creating Tables
- Python Word Count Method (re.findall)
- Python String Literal: F, R Strings
- Python MySQL Update Operation
- Python MySQL Join Operation
- Python Armstrong Number
- Learn Python Tutorial
- Python Factorial Number using Recursion
- Python Features
- Python Comments
- Python if else
- Python Translate and Maketrans Examples
- Python Website Blocker | Building Python Script
- Python Itertools Module: Cycle and Repeat
- Python Operators
- Python Int Example
- Python join Example: Combine Strings From List
- Python Read CSV File
- Python Write CSV File
- Python Read Excel File
- Python Write Excel File
- Python json: Import JSON, load and dumps
- Python Lambda Expressions
- Python Print the Fibonacci sequence
- Python format Example (Format Literal)
- Python Namedtuple Example
- Python SciPy Tutorial
- Python Applications
- Python KeyError Fix: Use Dictionary get
- Python Resize List: Slice and Append
- Python String | translate() method with Examples
- Python Copy List (Slice Entire List)
- Python None: TypeError, NoneType Has No Length
- Python MySQL Performing Transactions
- Python String | isnumeric() method with Examples
- Python MongoDB Example
- Python String | isprintable() method with Examples
- Python Tkinter Canvas
- Python String | isspace() method with Examples
- Python Tkinter Frame
- Python Tkinter Label
- Python Tkinter Listbox
- Python String | istitle() method with Examples
- Python Website Blocker | Script Deployment on Linux
- Python Website Blocker | Script Deployment on Windows
- Python String | isupper() method with Examples
- Python String split() method with Examples
- Python Slice Examples: Start, Stop and Step
- Python String | join() method with Examples
- Python String | ljust() method with Examples
- Python Sort by File Size
- Python Arithmetic Operations
- Python String | lower() method with Examples
- Python Exception Handling | Python try except
- Python Date
- Python Regex | Regular Expression
- Python Sending Email using SMTP
- Python Command Line Arguments
- Python List Comprehension Examples
- Python Assert Keyword
- Python Set Examples
- Python Fibonacci Sequence
- Python Maze Pathfinding Example
- Python Memoize: Dictionary, functools.lru_cache
- Python Timeit, Repeat Examples
- Python Strip Examples
- Python asyncio Example: yield from asyncio.sleep
- Python String Between, Before and After Methods
- Python bool Use (Returns True or False)
- Python Counter Example
- Python frozenset: Immutable Sets
- Python Generator Examples: Yield, Expressions
- Python CSV: csv.reader and Sniffer
- Python globals, locals, vars and dir
- Python abs: Absolute Value
- Python gzip: Compression Examples
- Python Function Display Calendar
- Python Display Fibonacci Sequence Recursion
- Python String | lstrip() method with Examples
- Python del Operator (Remove at Index or Key)
- Python String | partition() method with Examples
- Python String | replace() method with Examples
- Python Zip Examples: Zip Objects
- Python String | rfind() method with Examples
- Python String | rindex() method with Examples
- Python String rjust() method with Examples
- Python String rpartition() method with Examples
- Python String rsplit() method with Examples
- Python Area Of Triangle
- Python Quadratic Equation
- Python swap two Variables
- Python Generate Random Number
- Python Convert Kilometers to Miles
- Python Convert Celsius to Fahrenheit
- Python Check Number Positive Negative or Zero
- Python Check Leap Year
- Python Check Prime Number
- Top 40 Python Pandas Interview Questions (2021)
- Python Check Armstrong Number
- Python SQLite Example
- Python Tkinter Button
- Python Find LCM
- Python Find HCF
- Python Tuple Examples
- Python String | rstrip() method with Examples
- Python String splitlines() method with Examples
- Python String | startswith() method with Examples
- Python String | swapcase() method with Examples
- Python Truncate String
- Python String | upper() method with Examples
- Python for: Loop Over String Characters
- Python String | zfill() method with Examples
- Python Sort Examples: Sorted List, Dictionary
- Python XML: Expat, StartElementHandler
- Python Urllib Usage: Urlopen, UrlParse
- Python File Handling (with open, write)
- Python Example
- Python variables
- Python Random Numbers: randint, random.choice
- Python assert, O Option
- Python Data Types
- Python keywords
- Python literals
- Python MySQL Insert Operation
- Python MySQL Read Operation
- Python ascii Example
- Python ASCII Table Generator: chr
- Python Range: For Loop, Create List From Range
- Python re.match Performance
- Python re.match, search Examples
- Python Tkinter Menubutton
- Python Tkinter Menu
- Python Tkinter Message
- Python Tkinter Radiobutton
- Python List Examples
- Python Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf