Skip to content

Data structure

Also called: data structures

Published:

Why do data structures matter?

NIST defines a data structure as an organisation of information, usually in memory, for better algorithm efficiency. Queues, stacks, linked lists, heaps, dictionaries and trees are the standard examples [1]. Most data structures come with their own algorithms for operations such as search, insert or balance, which keep the structure's properties intact [1]. A structure can also carry redundant information, such as the length of a list [1].

That is why the choice shows up directly in speed. Storing the same data in a different structure can make one operation cheap and another expensive.

List or deque: what does the difference look like in Python?

The Python tutorial shows a list working as a stack: append() pushes onto the top, pop() takes from the top, last in first out [2]. Using a list as a queue is another matter. Appends and pops at the end are fast, but inserting or popping at the front means every other element has to shift [2]. For queues, the tutorial points to collections.deque instead [2].

The numbers behind that advice: a deque appends and pops from either end at roughly O(1) cost, while a list pays O(n) in memory movement for pop(0) and insert(0, v) [3]. On a queue of a million waiting jobs, that gap is noticeable.

Which other built-in data structures does Python offer?

A dictionary maps keys to values. Keys must be immutable, so strings and numbers work but lists do not [2]. A set is an unordered collection with no duplicates. It answers membership questions quickly and supports operations such as union and intersection [2].

Frequently asked questions

How do data structures relate to algorithms?

Most data structures have algorithms for operations like search and insert. The structure organises the data and the algorithm works on that organisation.

Can a Python list be used as a queue?

Yes, but popping from the front is slow. collections.deque is the better fit for queues.

Sources

  1. data structure — NIST Dictionary of Algorithms and Data Structures
  2. 5. Data Structures — Python documentation
  3. collections — Container datatypes — Python documentation

Related terms