Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a Python data structure by asking five questions: Does order matter? Must the contents change? Are duplicates valid? Will you retrieve items by position, membership, or a named key? Is the task a first-in, first-out queue? For most programs, the practical choices are list, tuple, set, dict, and, for queues, collections.deque.

This guide explains what each structure does, shows runnable examples, and points out the cases where a superficially convenient choice creates bugs or unnecessary work.

Python data structures at a glance

Structure Mental model Use it when Watch for
list Mutable ordered sequence Items need order, indexing, slicing, or updates Removing from the front is inefficient for queue behavior
tuple Fixed sequence used to group values A group’s slots should not be reassigned A tuple can still contain mutable objects
set Unordered collection of unique elements Deduplication, membership tests, and set algebra Do not rely on display order
dict Unique keys mapped to values Lookup by a meaningful key Keys must be suitable hashable values
collections.deque Double-ended queue Fast appends and removals at either end It is a standard-library type, not a literal such as []

Lists: ordered collections you can change

A list keeps its elements in sequence order. You can retrieve an element by numeric index, take a slice, replace an element, append new values, or remove values. Lists may contain duplicates and values of different types, although keeping related types together usually makes code easier to understand.

# Mutable ordered collection
scores = [8, 10, 9]
scores.append(7)

print(scores)       # [8, 10, 9, 7]
print(scores[1])    # 10
print(scores[1:3])  # [10, 9]

scores[0] = 11
last = scores.pop()
print(last)         # 7

When a list is the right default

  • You need to preserve a sequence for later iteration.
  • You need indexing such as items[0] or a slice such as items[:5].
  • The collection grows, shrinks, or has elements replaced.
  • You want a list comprehension to transform or filter values.
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers if n % 2 == 1]
print(squares)  # [1, 9, 25]

A list is not the best model for every job. If you repeatedly remove the first element to process a queue, use deque instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tuples: fixed slots for grouped values

A tuple is a sequence whose individual slots cannot be reassigned. It is useful when several values form one conceptual record, such as the two coordinates of a point. Tuple packing creates a tuple; unpacking assigns its elements to separate names.

point = (3, 5)
x, y = point
print(x)  # 3
print(y)  # 5

# Packing also works without parentheses
rgb = 255, 128, 0
red, green, blue = rgb

This fails because the tuple’s slot is fixed:

point = (3, 5)
# point[0] = 4  # TypeError

Immutability applies to the tuple’s slots, not automatically to every object reachable through it. A tuple can contain a mutable list:

record = ("inbox", ["email", "chat"])
record[1].append("phone")
print(record)  # ('inbox', ['email', 'chat', 'phone'])

Use a tuple when the grouping should not have its members replaced. Use a list when the sequence itself is expected to change.

Sets: unique values and membership tests

A set stores unique elements and is unordered. Constructing a set removes duplicate values, but you should not rely on the order in which elements are displayed or iterated.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
seen = {"red", "blue", "red"}
print(seen)          # {'red', 'blue'} in an unspecified order
print("blue" in seen)  # True

empty_set = set()
empty_dict = {}

The distinction between the two empty literals matters: {} creates a dictionary, while set() creates an empty set.

Set operations

Set algebra expresses relationships without manually writing nested loops:

required = {"email", "calendar", "storage"}
installed = {"calendar", "storage", "maps"}

print(required | installed)  # union
print(required & installed)  # intersection
print(required - installed)  # in required, not installed
print(required ^ installed)  # in exactly one set

Use a set when duplicates have no meaning, when you need to test whether a value is present, or when union, intersection, difference, or symmetric difference describes the operation. Every element must be suitable for use in a set; mutable containers such as lists are not valid elements.

Dictionaries: look up values by key

A dictionary maps unique keys to values. Unlike a sequence, it is accessed by key rather than by a numeric position. Keys must be suitable immutable, hashable values; a list cannot be a dictionary key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
prices = {"tea": 3, "coffee": 4}
print(prices["tea"])  # 3

prices["coffee"] = 5
prices["cake"] = 6
removed = prices.pop("tea")
print(removed)         # 3
print(prices.keys())

Use in to test keys, not values:

if "coffee" in prices:
    print("Coffee is listed")

Comprehensions and safe lookup

cubes = {n: n ** 3 for n in range(1, 4)}
print(cubes)  # {1: 1, 2: 8, 3: 27}

quantity = prices.get("juice", 0)
print(quantity)  # 0 when the key is absent

Indexing with prices["juice"] raises KeyError if the key is absent. get lets you provide a default. Choose a dictionary when the question is “what value belongs to this identifier?” rather than “what is at position 2?”

Queues: FIFO processing with deque

A first-in, first-out (FIFO) queue returns items in the order they arrived. A list can represent one, but removing its first element shifts the remaining elements. The Python tutorial recommends collections.deque for fast appends and pops at both ends.

from collections import deque

queue = deque(["first", "second"])
queue.append("third")
print(queue.popleft())  # first
print(queue)           # deque(['second', 'third'])

queue.appendleft("urgent")
last = queue.pop()
print(last)             # third

Use append with popleft for ordinary FIFO work. Use appendleft or pop when the workflow genuinely needs the opposite end. A list remains appropriate if you need frequent indexing or slicing rather than queue operations.

How to choose: a practical decision path

  1. Need named lookup? Choose dict; the name or identifier is the key.
  2. Need only unique values or membership checks? Choose set.
  3. Need a FIFO queue? Choose collections.deque.
  4. Need an ordered sequence that changes? Choose list.
  5. Need a grouped sequence whose slots should stay fixed? Choose tuple.

Then check the element rules. A set element or dictionary key must be hashable. A tuple is hashable only when its contents permit it; a tuple containing a list cannot be used as a dictionary key. If you need to mutate nested data, make that mutability explicit rather than assuming a tuple makes everything immutable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common mistakes and fixes

Assuming a set has a stable order

Set order is not a presentation contract. Convert it to a list and sort it when deterministic output is required and the elements can be ordered:

tags = {"python", "data", "code"}
for tag in sorted(tags):
    print(tag)

Using a list as a dictionary key

This raises TypeError because a list is mutable. Use a tuple when the grouped key is logically fixed:

locations = {(52, 13): "Berlin"}
print(locations[(52, 13)])

Confusing an empty dictionary with an empty set

Write set() for an empty set and {} for an empty dictionary. This is a syntax distinction, not a stylistic preference.

Changing a collection while iterating

Mutating a list or dictionary during its own loop can skip entries or raise an error. Build a filtered result instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
values = [1, 2, 3, 4]
values = [value for value in values if value % 2 == 0]
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, memory, and reliability notes

These structures are behavior choices, not interchangeable spellings. The documentation’s explicit queue guidance is the important performance distinction here: repeatedly removing from the front of a list shifts other elements, while deque is designed for appends and pops at both ends. Do not infer a universal speed ranking for every operation from these examples.

  • Pick the structure whose operations match the workload.
  • Measure a real application if performance matters; input size, access patterns, and object contents affect results.
  • Keep keys and values clear and consistent so a dictionary remains understandable.
  • Do not expose set iteration order as part of an API or serialized format.
  • Use tuples to communicate fixed grouping, but document nested mutable values when they are intentional.

Or skip the browser setup

If you need screenshots of documentation, dashboards, or generated Python examples, ScreenshotNeo provides a GET-based screenshot API. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

One call returns PNG, JPEG, WebP, or PDF. The API also supports full-page captures with lazy images loaded, CSS-selector elements, dark mode, device presets, custom viewports, retina scale, PDF paper and page options, custom CSS and JavaScript, clicks, waits, blocked requests, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Using the ScreenshotNeo documentation for your key, capture a page with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://docs.python.org/3/tutorial/datastructures.html -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://docs.python.org/3/tutorial/datastructures.html"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://docs.python.org/3/tutorial/datastructures.html' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Every feature is included on every plan: 1,000 screenshots monthly free with no card, then Starter is $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000; annual billing provides two months free. Sign up for the free 1,000-shot plan.

Frequently Asked Questions

Can a tuple be used as a dictionary key?

Only when every value inside it is hashable. A tuple containing a list is not suitable as a key because the nested list is mutable.

Does a dictionary use numeric positions like a list?

No. Retrieve dictionary values with their keys. If your operation is inherently positional, a list or tuple is a clearer model.

Which structure removes duplicates while preserving input order?

A set removes duplicates but is unordered. If original order must be retained, build a separate ordered result while tracking seen values with a set.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.