Home
Python
Python: Data Structures
Daniel Nguyen
Daniel Nguyen
September 03, 2026
1 min

Python data structures organize and manage data efficiently. The four built-in collections are list, tuple, dict, and set.

1. Lists

A list is an ordered, mutable collection that allows duplicates.

fruits = ["apple", "banana", "orange"]
fruits.append("mango")
fruits.remove("banana")
fruits.sort()
print(fruits)
print(fruits[0])

Common methods: append(), extend(), insert(), remove(), pop(), sort(), and reverse().

2. Tuples

A tuple is an ordered, immutable collection that allows duplicates.

coordinates = (10, 20)
x, y = coordinates
single = (42,) # Single-element tuple

Tuples support indexing, slicing, and unpacking but cannot be modified after creation. However, mutable objects inside a tuple can still change.

3. Dictionaries

A dictionary stores key-value pairs. Keys must be hashable, and assigning an existing key updates its value.

user = {"name": "Alice", "age": 25}
user["age"] = 26
user["city"] = "Hanoi"
print(user.get("email")) # None
for key, value in user.items():
print(key, value)

Common methods: get(), keys(), values(), items(), update(), and pop().

4. Sets

A set stores unique, hashable elements and is useful for removing duplicates and performing mathematical set operations.

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric difference

Use add() to insert an element and discard() to remove one without raising an error if it is missing. Use set() to create an empty set.

5. Shallow Copy vs. Deep Copy

A shallow copy creates a new outer collection but shares references to nested objects. A deep copy recursively copies nested objects where supported.

import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]]
print(deep) # [[1, 2], [3, 4]]

Use shallow copies when sharing nested objects is acceptable, and deep copies when nested data must be independent.

Key Takeaways

StructureOrderedMutableDuplicates
listYesYesYes
tupleYesNoYes
dictYes*YesKeys: No
setNo guaranteed orderYesNo

*Dictionaries preserve insertion order in modern Python.

Choose the appropriate data structure based on how data needs to be accessed, modified, and organized.


Tags

#Python

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

AI
Building an AI Gateway with FastAPI
October 06, 2026
2 min
Dev98

Dev98

React · Next.js · Web development