4

I have a matrix for instance

a=[12,2,4,67,8,9,23]

and I would like a code that appends a value say 45 to it and removes the first value '12' so in essence I want to make

a = [2,4,67,8,9,23,45]

I want to work with regular matrices not numpy matrices so I can't use hstack or vstack How do I do this in python? Any help would be appreciated, thanks

1
  • This is not a sliding window; this is a circular buffer. Commented Nov 29, 2012 at 15:13

3 Answers 3

13

Use a deque.

http://docs.python.org/2/library/collections.html#collections.deque

>>> import collections
>>> d = collections.deque(maxlen=7)
>>> d.extend([12,2,4,67,8,9,23])
>>> d.append(45)
>>> print d
deque([2, 4, 67, 8, 9, 23, 45], maxlen=7)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but what does deque mean? And thanks for the answer but I think I will go with Marian's answers it is simpler
@user17151 deque = double-ended queue. If you have 20 values, it doesn't matter which you use. If you have 2 million values, the deque is the qay to go rather than a mere list.
@user17151: that's fine but a deque is more efficient since it won't have to copy the entire data structure each time an element is appended.
This makes the append operation more efficient, but accessing elements in the middle of the data structure is less efficient with a deque than with a list (O(n) vs O(1)).
3

The simplest way:

a = a[1:] + [45]

2 Comments

This is brilliant. Should have thought of it, I'm just a beginner in python. Thanks a lot
No problem, but FogleBird's answer is in fact more efficient if performance is a concern at all.
1

You can do this:

a=[12,2,4,67,8,9,23]
a.append(45)
a.pop(0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.