w3resource

Creating a memory view on a Python bytes object: Length and first bytes

Python Memory Views Data Type: Exercise-1 with Solution

Write a Python program that creates a memory view on a bytes object and prints the length and first 8 bytes.

Sample Solution:

Code:

def main():
    try:
        data = b"Python Exercises!"
        # Create memory view on data
        mem_data  = memoryview(data)        
        print("Memory View Length:", len(mem_data))
        # Print first 8 bytes
        print("First 8 Bytes:", mem_data[:8])
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Memory View Length: 17
First 8 Bytes: <memory at 0x00000266DBB4E1C8>

In the exercise above, we create a memory view named 'mem_data' on the 'data' bytes object using the "memoryview()" function. We then print the length of the memory view using the "len()" function and the first 8 bytes using slicing on the memory view.

Flowchart:

Flowchart: Creating a memory view on a Python bytes object: Length and first bytes.

Previous: Python Extended Data Type Memory Views Exercises Home.
Next: Converting Python memory view to bytes: Function and example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-memory-views-exercise-1.php