Python Forum
Shifting items in a list? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Shifting items in a list? (/thread-15956.html)



Shifting items in a list? - MuntyScruntfundle - Feb-07-2019

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.


RE: Shifting items in a list? - micseydel - Feb-07-2019

del floats[0]



RE: Shifting items in a list? - ichabod801 - Feb-07-2019

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.


RE: Shifting items in a list? - DeaD_EyE - Feb-08-2019

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))