Paul's Python CoursePPC

collections.deque

Not met yet

deque (say "deck") from collections is a list built for both ends. append and pop work at the right; appendleft and popleft work at the left; all four are O(1). Taking from an empty one raises IndexError. Give it maxlen and it keeps only that many: when it's full, adding at one end drops an item off the other. Turn it into a list with list(...) when you need to show it or hand out a copy.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks appendleft adds to the back of a deque, rather than the front.
  • Thinks a full deque with a maxlen refuses new items or raises an error, rather than dropping one from the other end.
  • Thinks popleft on an empty deque gives None, rather than raising an IndexError.

Where it comes up