Coding

What Is a Data Structure? Definition and Python Examples

A data structure is a way of organizing data in memory so a program can store, find and change it efficiently. A Python list, a dictionary and a set are all data structures, and each one makes some operations cheap and others expensive.

The definition is short, but the useful part is the last clause: no structure is best at everything. Choosing one means choosing which operations you want to be fast.

What a data structure is, in plain terms

A single value, such as the number 42 or the string "hello", has a data type. Once you have many values, you need rules for how they sit together: in a fixed order, by name, with or without duplicates, last-in first-out, and so on. A data structure is that arrangement plus the operations it supports, such as add, remove, look up and iterate.

Take a phone book. You can store it as a pile of cards in no particular order, as a list sorted by surname, or as an index that jumps straight to a letter. All three hold the same information. Finding a number is slow in the pile, quicker in the sorted list and quickest with the index, while adding a new entry is easiest in the pile. Software has the same trade-off, only with millions of entries instead of hundreds.

Data structures built into Python

The Python tutorial chapter on data structures covers the four you will use most.

StructurePython typeWhat the docs say
Ordered, changeable sequencelistLists are mutable, and their elements are usually homogeneous and accessed by iterating over the list.
Ordered, fixed sequencetupleTuples are immutable, and usually contain a heterogeneous sequence of elements accessed by unpacking or indexing.
Unordered, no duplicatessetAn unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries.
Key to value mappingdictIndexed by keys, which can be any immutable type. Think of it as a set of key: value pairs with unique keys.

A short example showing why you would pick each:

scores = [88, 92, 75]            # list: ordered, you can append more
point = (51.5, -0.12)            # tuple: a fixed pair, should not change
tags = {"python", "sql", "api"}  # set: each tag appears once
ages = {"alex": 31, "sam": 27}   # dict: look up a value by name

scores.append(60)
print(ages["sam"])               # example output: 27
print("sql" in tags)             # example output: True

If you build lists from other lists a lot, the article on Python list comprehensions shows the compact syntax for it.

Why the choice matters: cost of operations

The Python documentation publishes the cost of each operation on its built-in types, in Time complexity of built-in types. The notation O(1) means the time does not grow with the number of items. O(n) means it grows in step with the number of items. Here are the figures for the operations people use most.

Operationlistdict
Read by index or keyO(1)O(1) average, O(n) worst case
Add at the endO(1) amortizedO(1) average (d[key] = value)
Insert at position kO(n - k)not applicable
Is a value present? (x in ...)O(n)O(1) average, O(n) worst case

The last row is the one that bites in practice. Checking x in some_list scans the list from the start, so doing it once per item in another large list gets slow quickly. Checking x in some_set or x in some_dict uses hashing and stays O(1) on average. The documentation notes that the dict worst case happens when every key hashes to the same value, which is rare with ordinary keys.

A concrete case: you have 100,000 user IDs in a list and want to know which of 100,000 incoming IDs are already known. With a list that is up to 100,000 comparisons for each incoming ID. Converting the list to a set once with known = set(known_list) makes each check a single hash lookup on average.

Stacks and queues

Some structures are defined by the order in which items come out rather than by how they are stored.

  • Stack: last in, first out. Think of a pile of plates. Undo history and function call tracking work this way.
  • Queue: first in, first out. Think of a line at a shop. Print jobs and task backlogs work this way.

Python's tutorial says a list makes a good stack: append() adds to the top and pop() without an index takes from the top.

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack.pop()      # example output: 7

A list is a poor queue, though. The tutorial explains that appends and pops at the end are fast, while inserts or pops at the beginning are slow because every other element has to be shifted by one. For a queue it recommends collections.deque:

from collections import deque

queue = deque(["Eric", "John", "Michael"])
queue.popleft()  # example output: 'Eric'

The deque documentation gives the reason: appends and pops from either side have approximately the same O(1) performance in either direction, while a list pays O(n) memory movement for pop(0) and insert(0, v). The same page lists a trade-off in the other direction. Indexed access in a deque is O(1) at both ends but slows to O(n) in the middle, so for fast random access it says to use a list. This is the pattern in miniature: same job, two structures, opposite strengths.

Other structures you will meet

Python does not build in every structure, but the names come up in interviews, documentation and libraries.

  • Linked list: items stored as nodes, each pointing to the next. Inserting in the middle is cheap once you hold a node, but finding the node means walking the chain.
  • Tree: nodes with parent and child links, with one root. File system folders and HTML documents are trees. A binary search tree keeps items ordered so lookups can skip half the remaining items at each step.
  • Heap: a tree arranged so the smallest (or largest) item is always at the top. It suits priority queues, where you always want the most urgent task next. Python provides this in the heapq module.
  • Graph: nodes joined by edges, with no root requirement. Road maps, social networks and package dependencies are graphs.

Data structures versus algorithms

The two ideas are paired but different. A data structure holds the data. An algorithm is the sequence of steps that works on it, such as searching or sorting. The cost of an algorithm often depends on the structure underneath it: the same "does this ID exist?" question is a linear scan on a list and a hash lookup on a set.

How to choose one

  1. Write down the operations you will do most: read by position, look up by name, check membership, add at one end, remove from the other end.
  2. Match them to a structure: ordered and indexed means list, lookup by name means dict, membership and uniqueness means set, first-in first-out means deque.
  3. Check whether you need to change the data after creating it. If not, a tuple signals that, and it can be used where an immutable value is required.
  4. Measure only if the data is large or the code is slow. For a few dozen items, the simplest structure is the right one.

If you are unsure, start with a list or a dict. They cover most programs, and the table above tells you when to switch.

Frequently asked questions

What are the most common data structures?
Arrays or lists, stacks, queues, hash tables (dictionaries), sets, linked lists, trees and graphs. Python ships list, tuple, set and dict as built-in types, and collections.deque in the standard library for fast queue operations.
What is the difference between a data type and a data structure?
A data type says what kind of value you have, such as an integer or a string. A data structure says how many values are organized together and which operations on them are cheap, such as a list that is fast to append to or a dict that is fast to look up by key.
Is a Python list an array?
It plays the same role as an array: an ordered sequence indexed by position, where reading l[k] takes constant time according to the Python documentation. Unlike arrays in many languages, a Python list can hold items of different types and grows as you append.
Do I need to learn data structures to write code?
You use them from the first program, because every list, dictionary or set is one. Learning how they differ matters once data gets large, when choosing a list where a set or dict fits can turn a fast program into a slow one.

Sources