Reading preferences
Concept

Abstract Data Types, Bags, and Deques

Separate what a collection promises from how it stores its items.

abstract data type, bag, deque, collection

A promise and its machinery

A vending machine promises certain buttons and results. Different machines can keep their snacks in different arrangements while keeping the same promise.

An abstract data type (ADT) describes a collection's allowed operations and their behaviour, rather than prescribing its internal layout. A stack promises last-in-first-out access; it can be backed by an array-like list or linked nodes. The same ADT can have implementations with different costs.

Bags and deques

A bag collects items without promising an order for removal; duplicates are allowed. A bag can collect scores before examining all of them. A set is different: it represents distinct values. Whether a particular bag supports removal is part of its own interface; some only support adding and iterating.

A deque (double-ended queue) supports adding and removing at both ends. It can support a queue or a stack and is useful when work may be added at either end.

appendleft(A)    append(B)       popleft()
    [A]            [A, B]          [B]
 front             front           front

See the reasoning

Follow the example one step at a time

Follow a deque as items are added and removed at either end. This is a prepared teaching demonstration, not live code execution.

Start empty

front [ ] back

A deque allows operations at both ends.

Python illustration

from collections import Counter, deque

bag = Counter(["red", "red", "blue"])
print("red count:", bag["red"])
line = deque()
line.appendleft("A")
line.append("B")
print("front:", line.popleft())
print("back:", line.pop())
print("empty:", not line)

Prepared output — not live execution:

red count: 2
front: A
back: B
empty: True

Here Counter records multiplicities for hashable values; it provides more operations than a minimal bag. deque is a concrete implementation, not the definition of every possible deque. Removing from an empty Python deque raises IndexError. Check or handle that condition.

Costs and common mistakes

Python documents approximately O(1) appends and pops at either end of a deque. Other implementations may have different costs. Counting and storing items requires space; a counter's space depends on distinct keys. Do not assume a bag gives sorted or first-in-first-out access, and do not assume an ADT alone guarantees a particular implementation's time complexity.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does an abstract data type describe?
2. Can a bag contain the same value twice?
3. At which ends can a deque add or remove items?
4. What does popleft do on an empty Python deque?

References and further reading