Python Forum

Full Version: Shifting items in a list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
del floats[0]
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.
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))