
When I started learning Python, I thought data structures were just another topic I needed to cover before moving on to building applications. Lists, tuples, dictionaries, and sets looked pretty straightforward. I could create them, add values, and print the results.
But when you start working on real projects, you realize that choosing the right data structure can make a big difference. It affects how readable your code is, how easily you can update data, and sometimes even how fast your application runs.
For example, imagine building an e-commerce application. You need to store product details, maintain a list of items in a cart, keep track of unique product categories, and manage orders. Using the same data structure for all these requirements would make the code harder to maintain.
Python provides several built-in data structures that solve these problems in different ways.
In this article, we’ll look at the most commonly used Python data structures, understand how they work, and explore where they make sense in real applications.
What Are Data Structures in Python?
A data structure is simply a way of organizing and storing data so that we can access and work with it efficiently.
Think about a real-world example. A contact book stores names and phone numbers. A shopping cart contains selected products. A queue at a ticket counter follows the order in which people arrive.
Each situation organizes information differently because the requirements are different.
Python provides four major built-in data structures:
List
Tuple
Set
Dictionary
These structures are easy to use, but each has its own behavior and purpose.
Let’s start with lists.
1. Python Lists
A list is one of the most frequently used data structures in Python. It stores multiple values in a single variable.
Lists are ordered, mutable, and allow duplicate values.
Ordered: Items maintain their insertion order.
Mutable: You can add, remove, or update items.
Duplicates allowed: The same value can appear more than once.
Here is a simple example:
languages = ["Python", "JavaScript", "Java", "Python"]
print(languages)Output:
['Python', 'JavaScript', 'Java', 'Python']Notice that Python appears twice. Lists allow duplicate values.
Accessing list elements
Python uses zero-based indexing, which means the first element is at index 0.
languages = ["Python", "JavaScript", "Java"]
print(languages[0]) # Python
print(languages[1]) # JavaScript
print(languages[-1]) # JavaNegative indexing is useful when you want to access items from the end of a list.
Adding elements
There are several ways to add elements to a list.
skills = ["Python", "JavaScript"]
skills.append("Node.js")
print(skills)append() adds an item to the end of the list.
If you want to add multiple values, use extend():
skills.extend(["React", "MongoDB"])
print(skills)You can also insert an element at a specific position:
skills.insert(1, "TypeScript")
print(skills)Updating and removing elements
Lists are mutable, so you can update values directly.
skills = ["Python", "JavaScript", "Java"]
skills[1] = "TypeScript"
print(skills)To remove an item by value:
skills.remove("Java")To remove an item by index:
skills.pop(0)The difference is important. remove() searches for a matching value, while pop() removes an item using its index and returns that item.
A real-world example: Shopping cart
A shopping cart is a good example of where a list can be useful.
cart = []
cart.append("Laptop")
cart.append("Mouse")
cart.append("Keyboard")
print("Cart items:", cart)
cart.remove("Mouse")
print("Updated cart:", cart)A list works well when you need to maintain an ordered collection of items.
However, if every product needs additional information such as price, quantity, and product ID, you might store dictionaries inside a list.
cart = [
{"product": "Laptop", "price": 60000, "quantity": 1},
{"product": "Mouse", "price": 800, "quantity": 2}
]
total = sum(item["price"] * item["quantity"] for item in cart)
print(total)This pattern is common in real applications: a list stores multiple records, while each dictionary stores the details of one record.
2. Python Tuples
A tuple is similar to a list, but it is immutable.
That means once a tuple is created, you cannot change its elements, add new elements, or remove existing ones.
coordinates = (10, 20)
print(coordinates[0])
print(coordinates[1])Trying to update a tuple will raise an error:
coordinates = (10, 20)
# This will raise a TypeError
coordinates[0] = 50Why use tuples?
You might wonder why we need tuples when lists already exist.
The answer is that sometimes data should remain unchanged.
For example, a geographic coordinate can be represented as a tuple:
location = (26.9124, 75.7873)
latitude = location[0]
longitude = location[1]The tuple makes it clear that these two values belong together and are not intended to be modified.
Tuples are also useful for returning multiple values from a function.
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
result = calculate(10, 5)
print(result)Output:
(15, 5)Python packs the returned values into a tuple.
You can unpack them directly:
total, difference = calculate(10, 5)
print(total)
print(difference)A small detail about single-element tuples
This is a common beginner mistake:
value = (10)
print(type(value))The result is int, not tuple.
To create a tuple containing one element, you need a comma:
value = (10,)
print(type(value))The comma is what makes it a tuple.
3. Python Sets
A set is a collection of unique elements.
Sets are useful when you want to remove duplicates or quickly check whether a value exists in a collection.
numbers = {1, 2, 3, 2, 1}
print(numbers)Output:
{1, 2, 3}Duplicate values are automatically removed.
One thing to remember: sets do not support indexing.
This will not work:
numbers = {10, 20, 30}
# numbers[0] # TypeErrorSets are designed for membership checks and set operations, not positional access.
Adding and removing values
skills = {"Python", "JavaScript"}
skills.add("React")
print(skills)To remove a value:
skills.remove("Python")If the value might not exist, discard() is safer because it does not raise an error.
skills.discard("Java")Removing duplicates from a list
One practical use of a set is removing duplicate values.
user_ids = [101, 102, 103, 101, 102, 104]
unique_ids = set(user_ids)
print(unique_ids)If you need a list again:
unique_ids = list(set(user_ids))Keep in mind that converting a list to a set does not preserve the original order as a guarantee. If order matters, you can use a different approach:
user_ids = [101, 102, 103, 101, 102, 104]
unique_ids = list(dict.fromkeys(user_ids))
print(unique_ids)This removes duplicates while preserving the first occurrence of each value.
Set operations
Sets support operations that are especially useful when comparing groups of data.
frontend = {"React", "Vue", "Angular"}
backend = {"Node.js", "Python", "React"}Union: Get all unique values from both sets.
print(frontend | backend)Intersection: Get values present in both sets.
print(frontend & backend)Difference: Get values present in one set but not the other.
print(frontend - backend)For example, these operations can help compare user permissions, identify common skills, or find products shared between two categories.
4. Python Dictionaries
A dictionary stores data in key-value pairs.
If you have worked with JavaScript objects, Python dictionaries will feel familiar.
user = {
"name": "Manjeet",
"role": "Full Stack Developer",
"experience": 3
}Here, "name", "role", and "experience" are keys. Their corresponding values are "Manjeet", "Full Stack Developer", and 3.
Dictionaries are mutable, and keys must be unique.
Accessing values
You can access a value using its key:
print(user["name"])However, if the key does not exist, Python raises a KeyError.
A safer option is get():
print(user.get("email"))If the key is missing, get() returns None by default.
You can also provide a fallback value:
print(user.get("email", "Not provided"))Updating dictionary values
user["experience"] = 4
user["city"] = "Jaipur"
print(user)If the key exists, its value is updated. If it does not exist, a new key-value pair is added.
Removing values
user.pop("city")You can also remove a key using del:
del user["role"]Looping through a dictionary
user = {
"name": "Manjeet",
"role": "Developer",
"experience": 3
}
for key, value in user.items():
print(key, value)The items() method returns key-value pairs, making it useful when you need both values in a loop.
A real-world example: API response data
Dictionaries are often used to represent JSON-like data in Python applications.
user = {
"id": 101,
"name": "Amit",
"email": "amit@example.com",
"is_active": True
}You can easily access individual properties:
if user["is_active"]:
print(f"Welcome, {user['name']}")This kind of structure is common when working with APIs, configuration files, and database records.
5. List vs Tuple vs Set vs Dictionary
The four data structures may look similar at first, but their use cases are different.
Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
Syntax |
|
|
|
|
Ordered | Yes | Yes | No positional order | Yes, insertion order |
Mutable | Yes | No | Yes | Yes |
Allows duplicates | Yes | Yes | No | Keys must be unique |
Indexing | Yes | Yes | No | Access by key |
Common use | Collection of items | Fixed group of values | Unique values | Key-value data |
A quick way to choose:
Use a list when you need an ordered collection that can change.
Use a tuple when you want a fixed collection of values.
Use a set when uniqueness or membership checking matters.
Use a dictionary when you need to look up values using keys.
6. Understanding Mutability
Mutability is an important concept in Python, especially when passing data to functions.
A mutable object can be changed after it is created. Lists, sets, and dictionaries are mutable.
Tuples are immutable, although a tuple can contain a mutable object such as a list.
Consider this example:
numbers = [1, 2, 3]
def update_list(items):
items.append(4)
update_list(numbers)
print(numbers)Output:
[1, 2, 3, 4]The function changes the original list because both variables refer to the same list object.
This can be useful, but it can also cause unexpected behavior if you are not careful.
For example, avoid using a mutable list as a default function argument:
def add_item(item, items=[]):
items.append(item)
return itemsThe default list is created once and reused between calls.
A better approach is to use None:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsThis creates a fresh list whenever no list is provided.
It is a small detail, but it can prevent some confusing bugs.
7. Choosing the Right Data Structure for Performance
Performance becomes more important as your application handles larger amounts of data.
For example, imagine checking whether a user ID exists in a list containing one million IDs.
user_ids = [101, 102, 103, 104, 105]
if 104 in user_ids:
print("User found")A list may need to inspect multiple elements before finding a match. In the worst case, it checks every element.
A set is generally better for repeated membership checks:
user_ids = {101, 102, 103, 104, 105}
if 104 in user_ids:
print("User found")Typical average-case time complexities for Python's built-in structures are:
Operation | List | Set | Dictionary |
|---|---|---|---|
Access by index | O(1) | Not supported | Not applicable |
Search by value/key | O(n) | O(1) average | O(1) average |
Append/add | O(1) amortized | O(1) average | O(1) average for adding a key |
Remove by value/key | O(n) for list search | O(1) average | O(1) average |
These are typical performance characteristics, not guarantees for every situation. Hash collisions, resizing, and the details of an operation can affect performance.
Also, don't optimize everything too early. For a small collection, a list might be perfectly fine. Choose the structure that makes the code clear, then measure performance when it becomes important.
8. A Practical Example: Counting Word Frequency
Let's put dictionaries and lists together in a simple example.
Suppose we have a sentence and want to count how many times each word appears.
sentence = "python is easy and python is powerful"
words = sentence.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print(frequency)Output:
{
'python': 2,
'is': 2,
'easy': 1,
'and': 1,
'powerful': 1
}Here is what happens:
split()converts the sentence into a list of words.The dictionary stores each word as a key.
get(word, 0)returns the current count, or0if the word is new.The count increases by one for every occurrence.
This pattern is useful for log analysis, text processing, basic analytics, and many other tasks.
Python also provides Counter from the collections module, which makes this particular job even simpler:
from collections import Counter
sentence = "python is easy and python is powerful"
frequency = Counter(sentence.split())
print(frequency)When a built-in library already solves a problem cleanly, there is no need to write extra code just to do it manually.
9. A Few Common Mistakes to Avoid
When working with Python data structures, keep these points in mind:
Using a set when order matters: Sets are great for uniqueness, but they are not designed for positional access.
Using a list for repeated membership checks: If you frequently check whether values exist in a large collection, a set may be more appropriate.
Accessing dictionary keys directly without checking: Use get() when a key might be missing.
Assuming a tuple makes everything inside it immutable: A tuple cannot have its own elements replaced, but it can contain mutable objects.
data = ([1, 2], 3)
data[0].append(4)
print(data)The list inside the tuple can still change.
Using mutable default arguments: Avoid default values like items=[] in function definitions. Use None and create a new object inside the function instead.
Conclusion
Python data structures are not just basic language features. They are tools that help you organize information and make your code easier to understand.
Lists are useful for ordered collections. Tuples are a good fit for fixed groups of values. Sets help manage unique elements, and dictionaries make key-based lookups simple.
As you build real applications, you will often combine these structures. A list might contain dictionaries, a dictionary might contain lists, and a set might help you remove duplicate values before saving data.
The most important thing is not memorizing every method. It is understanding what each structure is designed to do and choosing the one that matches the problem.
Start with small examples, experiment with the methods, and pay attention to how the data changes. Once you understand these basics, working with APIs, databases, automation scripts, and larger Python applications becomes much easier.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


