Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Shifting items in a list?
#1
Hi folks.

If I have a list of say, 150 values, all floats, how would I shift them all one place to the left and lose the first value. So move 1 to 0, 2 to 1, 3 to 2 etc.

Many thanks.
Quote
#2
del floats[0]
Quote
#3
your_list.pop(0). This also returns the first value. This is not very efficient. Depending on your application, you may want to reverse the list and use your_list.pop() to get and remove the last item, or look into collections.deque.
micseydel likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#4
collections.deque is for this an optimized datatype.

It has appendleft, popleft, pop, extendleft and rotate.
You can also initialize the deque with maxlen, which is the maximum size.

Example with moving average:

import collections


def moving_average(iterable, size):
    q = collections.deque(maxlen=size)
    for element in iterable:
        q.append(element)
        yield sum(q) / len(q)

r20 = range(20)
list(moving_average(r20, 5))
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Loop through array items dynamically in a certain format bhojendra 3 158 Jun-11-2019, 03:37 AM
Last Post: micseydel
  Count the number of items in a nested list iofhua 2 139 Jun-07-2019, 06:47 PM
Last Post: iofhua
  How to output set items without the curly braces ? jimthecanadian 3 181 May-11-2019, 07:02 AM
Last Post: perfringo
  shifting specific column to before/after specific column in dataframe theinzawoo 4 245 Mar-19-2019, 10:55 AM
Last Post: scidam
  Replacing list items dan789 3 251 Feb-01-2019, 02:48 PM
Last Post: perfringo
  converting the items of a list in new lists clarablanes 2 253 Jan-13-2019, 12:54 PM
Last Post: clarablanes
  Count of unique items based on condition JP_ROMANO 3 368 Dec-31-2018, 08:11 PM
Last Post: JP_ROMANO
  appending list items to other lists clarablanes 4 317 Dec-08-2018, 02:15 PM
Last Post: clarablanes
  [Outlook] How to delete items from To-Do List? Winfried 1 368 Oct-19-2018, 09:05 PM
Last Post: nilamo
  Join 2 items of array without a separator VoodooJia 3 412 Aug-29-2018, 06:01 PM
Last Post: VoodooJia

Forum Jump:


Users browsing this thread: 1 Guest(s)