Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
memoryview() in Python
Next article icon

memoryview() in Python

Last Updated : 22 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The memoryview() function in Python is used to create a memory view object that allows us to access and manipulate the internal data of an object without copying it. This is particularly useful for handling large datasets efficiently because it avoids the overhead of copying data. A memory view object exposes the buffer interface of the underlying object, such as bytes, bytearray or array, enabling direct access to the memory.

Example:

Python
# Creating a memory view of a bytearray data = bytearray("Hello", "utf-8")    mv = memoryview(data)                  print(mv[0])            mv[1] = 105            print(data)            

Output
72 bytearray(b'Hillo') 

Explanation:

  • A bytearray is created from the string "Hello" encoded as UTF-8.
  • memoryview() creates a view of the bytearray, allowing direct access to its memory.
  • Using indexing, the first byte is printed as an integer (ASCII value), and the second byte is modified, affecting the original bytearray.

Table of Content

  • Syntax of memoryview()
  • Different methods of using memoryview()
    • 1. Accessing bytes using indexing
    • 2. Modifying data using bytearray
    • 3. Converting memory view to bytes
    • 4. Using .cast() Method to Change Data Interpretation

Syntax of memoryview()

memoryview(object)

  • object: This must be an object that supports the buffer protocol, such as bytes, bytearray, or array.

Different methods of using memoryview()

1. Accessing bytes using indexing

Memory views can be accessed using indexing and slicing, similar to sequences like lists or strings. Indexing returns the byte value at the specified position as an integer, while slicing returns a new memory view representing the specified range of bytes. This approach is particularly useful for reading specific sections of large datasets without copying the entire data into memory, which improves efficiency.

Python
# Creating a memory view from bytes data = b'Python'          mv = memoryview(data)      # Accessing individual byte using indexing print(mv[0])               # Accessing a range of bytes using slicing print(mv[1:4].tobytes())  

Output
80 b'yth' 

Explanation:

  • The b'Python' is a bytes object, which is immutable and supports the buffer protocol.
  • memoryview(data) creates a view of this bytes object without copying the data.
  • mv[0] accesses the first byte, which is P with an ASCII value of 80.
  • mv[1:4] slices the memory view from index 1 to 3, resulting in b'yth', and .tobytes() converts this slice into an immutable bytes object.

2. Modifying data using bytearray

When using a mutable object like bytearray, memoryview() allows direct modification of the underlying data. Indexing can be used to update specific bytes by assigning new values (as integers representing ASCII codes). Any modifications made through the memory view immediately affect the original object. This capability is valuable for performance-critical applications where data needs to be modified without creating copies, such as image manipulation or real-time data processing.

Example:

Python
# Creating a bytearray for mutable data arr = bytearray(b'abcde')   mv = memoryview(arr)         # Modifying a byte using indexing mv[0] = 65                   print(arr)               

Output
bytearray(b'Abcde') 

Explanation:

  • The bytearray(b'abcde') is mutable, meaning its contents can be changed.
  • memoryview(arr) creates a view that references the bytearray directly.
  • Using mv[0] = 65 updates the first byte of the memory view to 65, which corresponds to the ASCII value of 'A'.
  • This modification reflects immediately in the original bytearray, as shown by print(arr) displaying bytearray(b'Abcde').

3. Converting memory view to bytes

The .tobytes() method converts the memory view into an immutable bytes object, which is a copy of the original data. This is useful when you need to create a read-only snapshot of the data that won’t be affected by future changes to the original buffer. The resulting bytes object can be safely shared between functions or stored for later use, ensuring data integrity. This method is commonly used in networking, data serialization, and cryptography.

Example:

Python
# Creating a mutable bytearray arr = bytearray(b'12345')   mv=memoryview(arr)  # Converting the memory view to immutable bytes result = mv.tobytes()         print(result)                 print(type(result))          

Output
b'12345' <class 'bytes'> 

Explanation:

  • The bytearray(b'12345') is a mutable sequence of bytes, each representing a character's ASCII value.
  • memoryview(arr) creates a view of this data without copying it.
  • The .tobytes() method creates an immutable copy of the entire memory view as a bytes object.
  • Even if the original bytearray is modified afterward, the bytes object returned by .tobytes() remains unchanged, ensuring data consistency.

4. Using .cast() Method to Change Data Interpretation

The .cast() method allows you to reinterpret the underlying memory as a different data type without altering the actual data. This method is particularly useful for working with binary data or structured data formats, where the same bytes can represent different types depending on their interpretation. By specifying a format code (like 'B' for unsigned bytes or 'i' for integers), you can access the memory as a sequence of different-sized elements, which is essential for tasks like parsing binary files, network protocols, and image processing.

Python
import array  # Creating an array of integers arr = array.array('i', [1, 2, 3, 4])    mv=memoryview(arr)  # Reinterpreting the data as unsigned bytes mv_cast = mv.cast('B')                 print(mv_cast.tolist())                

Output
[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0] 

Explanation:

  • The array.array('i', [1, 2, 3, 4]) creates an array of integers, where each integer typically occupies 4 bytes.
  • memoryview(arr) creates a view of this array, allowing access to its underlying memory.
  • .cast('B') reinterprets the same memory as a sequence of unsigned bytes (B), effectively splitting each integer into 4 separate bytes.
  • The .tolist() method then returns these bytes as a list of integers, providing a human readable representation of the raw memory contents.

Next Article
memoryview() in Python

S

Shivani Ghughtyal
Improve
Article Tags :
  • Python
  • Python-Built-in-functions
Practice Tags :
  • python

Similar Reads

    eval in Python
    Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None)Parameters:expression: String is parsed and evaluated as a Python expressio
    5 min read
    filter() in python
    The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:Example Usage of filter()Python# Function to check if a number is even def even(n): return n % 2 == 0 a = [1
    3 min read
    float() in Python
    Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. Python3 # convert integer value to floa
    3 min read
    Python String format() Method
    format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E
    8 min read
    Python - globals() function
    In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
    2 min read
    Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary.Python hash() function SyntaxSyntax : hash(obj)Parameters : obj : The object which we need t
    6 min read
    hex() function in Python
    hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example:Pythona = 255 res = hex(a) print(res)Output0xff Explanat
    2 min read
    id() function in Python
    In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
    3 min read
    Python 3 - input() function
    In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string.Python input() Function SyntaxSyntax: input(prompt)Parameter:Prompt: (optional
    3 min read
    Python int() Function
    The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part.Example:In this example, we passed a string as an argument to the int() function and printed it.Pythonage = "21" print("age =", int(age)
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences