On Mon, 16 Dec 2013 15:59:32 +1100, Ben Finney wrote: > shengjie.sheng...@live.com writes: > >> Hi guys, I am trying to create a fixed list which would allow my values >> to be wrapped around it. > > This doesn't make a lot of sense to me, but I assume you have a purpose > in mind for this. What is the purpose? Perhaps it will help the > explanation if we know what it's for. > >> For example i have 10 values : 0,1,2,3,4,5,6,7,8,9 > > Does this mean the input is a list, ‘[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]’? Or > do you mean something else? What is the input? > >> I need to create a list which contains 4 numbers and when the number >> exceeds the list, it would overwrite the first value. > >> [0,1,2,3] >> [4,1,2,3] >> [5,4,1,2] > > That's three different lists. What is the input in each case? Under what > circumstances would you expect each one to be produced?
I suspect the OP means: first input is 0, list = [ 0 ] next input is 1, list = [ 0, 1 ] next input is 2, list = [ 0, 1, 2 ] next input is 3, list = [ 0, 1, 2, 3 ] next input is 4, list = [ 4, 1, 2, 3 ] next input is 5, list = [ 5, 4, 1, 2 ] But this is a bit daft, because he starts by appending, and when he hits overflow he starts prepending. What I think he should do is use collections.dequeue and a couple of helper functions to add and get data items. For a queue moving from position 0 to position 3 (left to right): from collections import deque q = dequeue([]) def add_to_queue( item, q ): if len( q ) is 4: q.pop() q.appendleft( item ) def get_next( q ): if len( q ) > 0: return q.pop() return None To move from position 3 to position 0 (right to left), swap pop and appendleft for popleft and append. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list