w3resource

Reversing memory views in Python: Example and steps


Write a Python program that creates a memory view from a bytearray, reverses the order using slicing, and converts back to a bytearray.

Sample Solution:

Code:

def test(memory_view):
    reversed_memory_view = memory_view[::-1]
    return bytearray(reversed_memory_view)

def main():
    original_data = bytearray([10, 20, 30, 40, 50])
    original_memory_view = memoryview(original_data)
    print("Original Data:", original_data)
    print("Original Memory View:", original_memory_view.tolist())
    reversed_bytearray = test(original_memory_view)
    print("Reversed Bytearray:", reversed_bytearray)
if __name__ == "__main__":
    main()

Output:

Original Data: bytearray(b'\n\x14\x1e(2')
Original Memory View: [10, 20, 30, 40, 50]
Reversed Bytearray: bytearray(b'2(\x1e\x14\n')

In the exercise above, using slicing with the [::-1] notation, the "test()" function reverses the order of elements in a memory view, and then creates a new bytearray based on the reversed memory view.

The "main()" function creates an original bytearray, converts it to a memory view, and prints the original data and memory view. Then, it calls the "test()" function to reverse the memory view and convert it back to a bytearray . Finally, it prints the reversed bytearray.

Flowchart:

Flowchart: Reversing memory views in Python: Example and steps.

Previous: Iterating and modifying memory views in Python: Example.
Next: Slicing memory views in Python: Indexing syntax and example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.