Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create array in python that keeps its length fixed?

For real time plotting the COM port data in python, I need to make a fixed length array, if new value is received it keeps it at last index and when array is filled, upon next update, it dumps value at 1st index. In other words it keeps latest value at last index and empties value at first index (to keep length fixed)

like image 721
Talha Yousuf Avatar asked Mar 26 '26 07:03

Talha Yousuf


1 Answers

What you described is basically a fixed-length double-ended queue (often called deque).

You can use Python's built-in deque:

from collections import deque

d = deque(maxlen=2)

for i in range(10):
    d.append(i)
    print(d)

# deque([0], maxlen=2)
# deque([0, 1], maxlen=2)
# deque([1, 2], maxlen=2)
# deque([2, 3], maxlen=2)
# deque([3, 4], maxlen=2)
# deque([4, 5], maxlen=2)
# deque([5, 6], maxlen=2)
# deque([6, 7], maxlen=2)
# deque([7, 8], maxlen=2)
# deque([8, 9], maxlen=2)

You may also use appendleft instead of append:

for i in range(10):
    d.appendleft(i)
    print(d)

# deque([0], maxlen=2)
# deque([1, 0], maxlen=2)
# deque([2, 1], maxlen=2)
# deque([3, 2], maxlen=2)
# deque([4, 3], maxlen=2)
# deque([5, 4], maxlen=2)
# deque([6, 5], maxlen=2)
# deque([7, 6], maxlen=2)
# deque([8, 7], maxlen=2)
# deque([9, 8], maxlen=2)


Alternatively, if you want it the other way around you can inherit list and implement append yourself. Note the slightly different result:

class MyList(list):
    def __init__(self, max_len, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_len = max_len

    def append(self, obj):
        if len(self) < self.max_len:
            super().append(obj)
        else:
            self.insert(0, obj)  # inserting to the left
            self.pop()           # deleting the last element on the right

li = MyList(2)

for i in range(10):
    li.append(i)
    print(li)

# [0]
# [0, 1]
# [2, 0]
# [3, 2]
# [4, 3]
# [5, 4]
# [6, 5]
# [7, 6]
# [8, 7]
# [9, 8]
like image 70
DeepSpace Avatar answered Mar 28 '26 21:03

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!