w3resource

Iterating and modifying memory views in Python: Example

Python Memory Views Data Type: Exercise-7 with Solution

Write a Python program that iterates over a memory view and increment each element by 10 using a loop.

Sample Solution:

Code:

def test(memory_view):
    for i in range(len(memory_view)):
        memory_view[i] = (memory_view[i] + 10) % 256
def main():
    data = bytearray([100, 200, 150, 200, 50])
    memory_view = memoryview(data)
    print("Original Memory View:", memory_view.tolist())
    test(memory_view)
    print("Modified Memory View:", memory_view.tolist())
if __name__ == "__main__":
    main()

Output:

Original Memory View: [100, 200, 150, 200, 50]
Modified Memory View: [110, 210, 160, 210, 60]

In the exercise above, the "test()" function takes a memory view as an argument and iterates over its elements using a loop. It increments each element by 10 and uses the modulo operation to ensure that the values stay within the valid range of 0 to 255. The "main()" function creates a bytearray, converts it to a memory view. Prints the original memory view, calls the "test()" function to modify the memory view, and then prints the modified memory view.

Flowchart:

Flowchart: Iterating and modifying memory views in Python: Example.

Previous: Concatenating memory views in Python: Function and example.
Next: Reversing memory views in Python: Example and steps.

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.