Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #62025

Re: Wrapping around a list in Python.

From Peter Otten <__peter__@web.de>
Subject Re: Wrapping around a list in Python.
Date 2013-12-16 10:15 +0100
Organization None
References <e8123076-9f52-4a72-b262-908a5dcc8a10@googlegroups.com> <mailman.4181.1387171006.18130.python-list@python.org> <cf42bb27-a2c9-4a94-9c74-a6ff1253a2ee@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.4188.1387185319.18130.python-list@python.org> (permalink)

Show all headers | View raw


shengjie.shengjie@live.com wrote:

> The idea is to grab the last 4 elements of the array. However i have an
> array that contains a few hundred elements in it. And the values continues
> to .append over time. How would i be able to display the last 4 elements
> of the array under such a condition?

Use a deque:

>>> from collections import deque
>>> last_four = deque(maxlen=4)
>>> for i in range(10):
...     last_four.append(i)
... 
>>> last_four
deque([6, 7, 8, 9], maxlen=4)
>>> last_four.extend(range(100, 200))
>>> last_four
deque([196, 197, 198, 199], maxlen=4)
>>> last_four.append(42)
>>> last_four
deque([197, 198, 199, 42], maxlen=4)

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Wrapping around a list in Python. shengjie.shengjie@live.com - 2013-12-15 20:38 -0800
  Re: Wrapping around a list in Python. Ben Finney <ben+python@benfinney.id.au> - 2013-12-16 15:59 +1100
    Re: Wrapping around a list in Python. shengjie.shengjie@live.com - 2013-12-15 21:07 -0800
      Re: Wrapping around a list in Python. shengjie.shengjie@live.com - 2013-12-15 21:10 -0800
        Re: Wrapping around a list in Python. Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-12-16 09:33 +0000
    Re: Wrapping around a list in Python. Denis McMahon <denismfmcmahon@gmail.com> - 2013-12-16 10:12 +0000
  Re: Wrapping around a list in Python. Gary Herron <gary.herron@islandtraining.com> - 2013-12-15 21:10 -0800
    Re: Wrapping around a list in Python. shengjie.shengjie@live.com - 2013-12-15 21:26 -0800
      Re: Wrapping around a list in Python. Peter Otten <__peter__@web.de> - 2013-12-16 10:15 +0100
      Re: Wrapping around a list in Python. David Robinow <drobinow@gmail.com> - 2013-12-16 07:41 -0500
      Re: Wrapping around a list in Python. Dave Angel <davea@davea.name> - 2013-12-16 07:51 -0500
  Re: Wrapping around a list in Python. shengjie.shengjie@live.com - 2013-12-15 21:26 -0800

csiph-web