🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeData Structures in Python and When to Use Them

As you add values to a Python program, you have to decide how the code should store and access them. A data structure organizes values that a program can work with.
I’ll explain what Python data structures are and show how to choose a collection for the operation you need.
TL;DR
Choose a Python collection by the operation your code needs: ordered items, a fixed record, key lookup, or unique membership.
- Use a list for an ordered sequence that changes.
- Use a tuple for a fixed, positional record.
- Use a dictionary to map keys to values.
- Use a set when values must be unique and order does not matter.
What Are Data Structures in Python?
A data structure organizes values so a program can work with them. In Python, lists, tuples, dictionaries, and sets are four common built-in collection types. Choose a list for an ordered collection because its contents can change in place.

A list and a tuple are positional sequences, so either fits when item position matters. Because the list sample changes its contents in place, choose a list when an ordered collection must change. A tuple holds fixed item slots and can represent a small record, such as an x and y coordinate.
A dictionary maps keys to values. A set holds unique values without positions. Dictionary and set lookups both use hashing, but only dictionaries preserve insertion order in Python 3.7 and later.
| Type | Access | Can change? | Useful when |
|---|---|---|---|
| list | Position or iteration | Yes | Items form an ordered sequence |
| tuple | Position or unpacking | No, not its slots | Positions describe one fixed record |
| dict | Key | Yes | Each key identifies a value |
| set | Membership | Yes | Duplicates should collapse |
The four are a starting point, not a complete catalogue of available containers. A stack or queue describes an access rule. A graph describes relationships between nodes and usually needs a representation built from Python objects and containers.
For homogeneous numeric values, array.array offers compact typed storage. Unlike a general list, it constrains its values to one type code.
How Do Strings, Searching, and Sorting Fit In?
A string is another sequence type, while search and sort are operations. Choose a string for characters or substrings because its contents are text.
Index a string to read one character, or take a slice to make a substring.
Because a string cannot be changed in place, a text transformation returns a new string. Sorting text with sorted() returns a list of characters, not another string.
| Task | Operation to consider | Behavior to remember |
|---|---|---|
| Find text inside text | String membership or find() | find() returns -1 when no match exists. |
| Find an item in an unsorted list | Membership or a loop | Checks proceed through the sequence until a match. |
| Search a sorted sequence repeatedly | bisect | Keep the values sorted before searching. |
| Keep the original sequence | sorted(values) | A new sorted list is returned. |
| Reorder a list in place | values.sort() | The existing list changes and the method returns None. |
| Handle a missing substring | find() or index() | find() returns -1. index() raises ValueError. |
Use membership to ask whether text contains a substring or whether an unsorted list holds an item. String membership checks each case exactly, so casefold both text values first when a caseless search is needed.
Because bisect uses binary search, lookup needs logarithmic comparisons when the sequence stays sorted. Inserting a value in the middle of a Python list still shifts later entries, so frequent updates can outweigh those savings.
Use sorted(values) to build a new list. Call list.sort() to reorder an existing list in place, and remember that it returns None. Both accept a key function that extracts a comparison field once for each item, so choose based on whether the source must stay unchanged.
How to Choose and Use Python Data Structures Step by Step
Each example checks one operation on a collection. I ran each named file with Python 3.14.7 and placed its captured output beside a screenshot of that run.
Step 1: Use a list for a sequence you will change
Use append() for one value. Use extend() to add an iterable’s items separately. If the input is [3, 4], append() nests that list, whereas extend() adds its two values.
orders = ["packing", "labeling"]
orders.append("dispatch")
removed = orders.pop()
print(f"After append: {orders}")
print(f"Popped from the end: {removed}")
python3 list_demo.py
After append: ['packing', 'labeling']
Popped from the end: dispatch

The popped value is dispatch because pop() without an index removes the final item. That is a good fit for a stack. It is not a good way to remove the first item repeatedly from a long queue, because the remaining list items have to shift.
Step 2: Use a tuple for a fixed record
Unpacking assigns the two tuple values to x and y together. A one-item tuple needs a trailing comma because parentheses by themselves only group a value.
coordinates = (4, 9)
x, y = coordinates
print(f"Coordinates: x={x}, y={y}")
python3 tuple_demo.py
Coordinates: x=4, y=9

Step 3: Use a dictionary for key-value lookup
This demo updates one price under its key, then asks for a fallback on a missing key. Assigning to an existing key replaces its value rather than adding a duplicate.
prices = {"tea": 12, "coffee": 7}
prices["tea"] = 13
print(f"Tea: {prices['tea']}")
print(f"Missing item default: {prices.get('juice', 0)}")
python3 dict_demo.py
Tea: 13
Missing item default: 0

Dictionary keys are unique, so assigning to tea changes its associated value instead of adding a second tea entry. A dictionary also preserves the order in which keys were inserted. Choose it when the key names a value, not merely because it can hold a mix of objects.
By default, get() returns None for an absent key. If None is also a valid stored value, pass a unique sentinel as the default when code must distinguish absence from a stored None.
Step 4: Use a set to keep unique values
Build a set from values that may repeat, then check a candidate with in. This example compares the number of stored values with the number of values written in the literal.
items = {"pear", "apple", "pear"}
print(f"Unique items: {len(items)}")
print(f"Contains pear: {'pear' in items}")
python3 set_demo.py
Unique items: 2
Contains pear: True

The repeated pear is stored once, so the count is two. Sets also support union, intersection, and difference to create a new result from two inputs. Sort values before displaying them when a stable sequence is needed.
Which Python Data Structure Edge Cases Should You Check?
Because a type can fail at its boundaries, check how it handles missing values before choosing. Then compare its key rules with the way items enter and leave the collection.
A FIFO queue retrieves earlier arrivals first. collections.deque can add at the right and remove from the left without shifting every remaining item. Use heapq when priority determines which item comes next, because its min-heap keeps the smallest value at the root.
| Case | What happens | What to do |
|---|---|---|
| Empty braces | {} creates an empty dictionary, not an empty set. | Call set() for an empty set. |
| Single-element tuple | Parentheses alone do not create a tuple. | Write the item followed by a comma. |
| Mutable tuple member | The tuple slot stays fixed, but a list stored inside it can still change. | Do not treat tuple immutability as a deep freeze. |
| Unhashable key or member | A list cannot be a dictionary key or a set element. | Choose an immutable value for a key or set member. |
| Missing dictionary key | Square-bracket lookup raises KeyError when the key is absent. | Use get() when a default is appropriate. Use brackets when absence should be an error. |
| Queue from a list | pop(0) removes the first item but shifts the remaining positions. | Use collections.deque and popleft() for FIFO work. |
| Set display order | Set elements have no promised display order for your logic. | Sort values before displaying or comparing an ordered result. |
| Repeated smallest-item retrieval | Sorting a collection after each change repeats work. | Use heapq when the next item should be the smallest priority. |
To inspect a value while debugging, type() reports its concrete type. In program logic, isinstance() checks whether a value belongs to a type or its subclass. Prefer testing the operation your function needs when that is more useful than branching on the exact container class.
A tuple can be a dictionary key or set member only when every item inside it is hashable. Numeric tuples qualify, while a tuple containing a list does not. Use frozenset when the unique values must remain immutable.
Because a second name points to the same list after assignment, use a shallow copy before changing the outer list independently. The two lists still share nested mutable items, so use a deep copy when those inner values also need to be independent.
Conclusion: Choose by the Operation You Need
List, tuple, dict, and set solve different access problems. Decide whether order, later changes, named lookup, or uniqueness matters, then pick the type whose behavior matches that requirement.
- Python’s official data structures tutorial covers built-in operations and list methods.
- The collections documentation explains deque, the heapq reference describes min-heaps, and the array documentation covers compact, typed sequences.
- Python’s sorting HOWTO and bisect documentation explain sorting and searching ordered sequences.
- AskPython’s list tutorial covers list operations in more detail.
- AskPython’s dictionary tutorial covers key-value lookup.
- AskPython’s tuple guide and set guide continue the comparison.
- AskPython’s Dijkstra guide shows a graph-based problem.
FAQ
These answers cover quick checks that come up after choosing a collection.
What are the four built-in data structures in Python?
The four general-purpose built-in collection types commonly introduced first are list, tuple, dictionary, and set. Python and its standard library provide other containers, and programs can define more.
How can I check a value’s type in Python?
Use type(value) to see its concrete type. Use isinstance(value, SomeType) when program logic should also accept subclasses.
Can a tuple contain a list?
Yes. The tuple keeps the same references in its slots, but the list inside it remains mutable. Such a tuple is not hashable and cannot be used as a dictionary key.


