Core Data Structures in Python: Lists, Tuples, Sets and Dictionaries
Part of the series Python Basics — part 2
In the previous post, Data Types in Python, we went through Python’s built-in types, including a quick look at lists, tuples, sets, and dictionaries.
These four are different from simple values like numbers and text because they are used to hold collections of values.
Python programs work with collections all the time. You might want to store a list of books, a group of unique tags, or information about a person. This is where data structures become useful.
But before we look at each data structure, there is one small thing that is really important to remember: the brackets you use matter.
Why are brackets important in Python?
When creating a data structure in Python, the brackets you use tell Python what kind of data structure you are creating.
For example, square brackets create a list:
books = ["The Bell Jar", "Convenience Store Woman", "Kafka on the Shore"]
But if you use square brackets when you are trying to create a tuple, you won’t get a tuple. You will create a list instead.
A tuple uses parentheses:
books = ("The Bell Jar", "Convenience Store Woman", "Kafka on the Shore")
Similarly, sets and dictionaries use curly braces, but they have different structures:
# Set
genres = {"fiction", "mystery", "history"}
# Dictionary
book = {"title": "The Bell Jar", "author": "Sylvia Plath"}
So, before creating a collection, remember which brackets belong to which data structure:
| Data structure | Brackets | Example |
|---|---|---|
| List | Square brackets [] | ["a", "b", "c"] |
| Tuple | Parentheses () | ("a", "b", "c") |
| Set | Curly braces {} | {"a", "b", "c"} |
| Dictionary | Curly braces {} | {"name": "Vinky"} |
Notice that sets and dictionaries both use curly braces. The difference is what you put inside them. A set contains individual values, while a dictionary contains key-value pairs.
One more small thing to remember: an empty dictionary is created with {}, while an empty set is created with set().
Now let’s look at each data structure individually.
Four commonly used data structures at a glance
Python has four commonly used built-in collection types: lists, tuples, sets, and dictionaries.
| Data structure | Brackets | Ordered? | Mutable? | Duplicates? |
|---|---|---|---|---|
| List | [] | Yes | Yes | Yes |
| Tuple | () | Yes | No | Yes |
| Set | {} | No | Yes | No |
| Dictionary | {} | Insertion-ordered | Yes | Keys are unique |
Let’s go through them one by one.
A. Lists
A list is an ordered, changeable collection. It is one of the most commonly used collection types in Python.
1. How to create a list
Lists are created using square brackets []:
books = ["The Bell Jar", "Convenience Store Woman", "Kafka on the Shore"]
You can also create an empty list:
books = []
A list can contain different types of values:
my_list = ["Anna", 32, True, 3.14]
Although Python allows this, you’ll often use lists to store related values.
2. Getting items
Lists are ordered, so each item has a position called an index.
Python starts counting from 0.
books = ["The Bell Jar", "Convenience Store Woman", "Kafka on the Shore"]
print(books[0])
print(books[1])
print(books[2])
Output:
The Bell Jar
Convenience Store Woman
Kafka on the Shore
3. Changing items in a list
Lists are mutable, which means we can change them after creating them.
fruits.append("orange") # add to the end
fruits.insert(1, "grape") # add at a specific position
fruits[0] = "kiwi" # replace an item
fruits.remove("mango") # remove by value
last = fruits.pop() # remove and return the last item
print(fruits) # ['kiwi', 'grape', 'banana', 'cherry']
print(last) # orange
books = ["The Bell Jar", "Convenience Store Woman", "Kafka on the Shore"]
books[1] = "Norwegian Wood"
print (books) # ['The Bell Jar', 'Norwegian Wood', 'Kafka on the Shore']
4. Other everyday list tools
Python gives us several useful methods for working with lists:
books.append("Pachinko") # append() adds an item to the end of the list
books.remove("Norwegian Wood") # remove() removes a specific item
books.sort() # sort() sorts the list in a place
books.reverse() # `reverse()` reverses the order of the items.
Note that .sort() changes the list itself and returns nothing. I used it in Python Coding Exercise #02 to print names in alphabetical order. The built-in sorted() function, in contrast, returns a new list and leaves the original alone; it is explained in Built-in Functions in Python. In Python Coding Exercise #41, sorted() is used to find the middle letter of three.
Functions such as len(), sum() and max() also work on lists. They are explained in Built-in Functions in Python, and Python Coding Exercise #50 uses them to calculate statistics from a list of numbers. Strings have their own tools for working with lists, such as split() and join(), which are explained in String Methods in Python.
numbers = [40, 5, 22, 13]
print(len(numbers)) # 4
print(sum(numbers)) # 80
print(max(numbers)) # 40
print(22 in numbers) # True
numbers.sort()
print(numbers) # [5, 13, 22, 40]
5. Looping over a list
We can use a for loop to go through each item:
books = ["The Bell Jar", "Convenience Store Woman", "Kafka on the Shore"]
for book in books:
print(book)
This prints each book on a separate line.
B. Tuples
A tuple is similar to a list because it is an ordered collection that can contain duplicate values.
The biggest difference is that a tuple cannot be changed in place after it is created.
1. How to create a tuple
Tuples are created using parentheses ():
exam_date = (2026, 10, 2)
print(exam_date[0]) # 2026
print(len(exam_date)) # 3
If you try to change a tuple, Python stops you:
exam_date[1] = 11
TypeError: 'tuple' object does not support item assignment
You can access tuple items using indexes just like lists.
2. Why use a tuple?
Since tuples cannot be changed in place, they can be useful when you want to group values that should stay together.
For example:
coordinates = (28.6139, 77.2090)
3. A common tuple mistake
Remember that square brackets create a list, not a tuple.
This:
books = ["The Bell Jar", "Convenience Store Woman"]
creates a list.
This:
books = ("The Bell Jar", "Convenience Store Woman")
creates a tuple.
There is also a small Python quirk when creating a tuple with only one item.
This is not a tuple:
book = ("The Bell Jar")
Python treats this as a string inside parentheses.
To create a one-item tuple, you need a trailing comma:
book = ("The Bell Jar",)
That comma is what makes it a tuple.
4. Assigning tuple values to separate variables
You can also take the values from a tuple and assign them to separate variables:
book = ("The Bell Jar", "Sylvia Plath")
title, author = book
print(title)
print(author)
Output:
The Bell Jar
Sylvia Plath
Here, Python takes the first value, "The Bell Jar", and assigns it to title.
It takes the second value, "Sylvia Plath", and assigns it to author.
So this:
title, author = book
is basically saying:
Take the values from
bookand put them into these two variables.
In Python, this is commonly called unpacking.
You’ll come across this term often when learning Python, so it’s useful to know the name, but the basic idea is simply putting the values into separate variables.
C. Sets
A set is a collection of unique values.
Unlike lists and tuples, sets do not support indexing, and you should not rely on an order when working with their elements.
1. How to create a set
Sets are created using curly braces **{}**:
genres = {"fiction", "mystery", "history"}
A set automatically removes duplicate values:
genres = {"fiction", "fiction", "mystery", "history"}
print(genres)
The result contains only one "fiction".
Sets can be particularly useful when you want to remove duplicates from a collection or check whether a value exists in a group of unique values.
For example:
books = ["fiction", "mystery", "fiction", "history"]
unique_genres = set(books)
print(unique_genres)
2. Removing duplicates
The most common use for a set is removing duplicates from a list:
scores = [90, 75, 90, 60, 75]
unique_scores = set(scores)
print(len(scores)) # 5
print(len(unique_scores)) # 3
3. Comparing two groups
Sets also make it easy to compare groups of items:
python_class = {"anna", "ben", "carla"}
java_class = {"ben", "carla", "dev"}
print(sorted(python_class & java_class)) # ['ben', 'carla'] (in both)
print(sorted(python_class | java_class)) # ['anna', 'ben', 'carla', 'dev'] (in either)
print(sorted(python_class - java_class)) # ['anna'] (in the Python class only)
You can also add items with .add() and check membership with in, which is very fast even for large sets.
3. A common sets mistake
Remember that {} creates an empty dictionary, not an empty set.
To create an empty set, use:
my_set = set()
So:
{}
is an empty dictionary, while:
set()
is an empty set.
D. Dictionaries
A dictionary stores data as key-value pairs. Instead of looking items up by position, you look them up by name.
1. How to create a dictionary
Dictionaries are created using curly braces **{}**, just like sets.
The difference is that dictionaries contain key-value pairs:
{"key": "value"}
For example:
student = {
"name": "Anna",
"age": 21,
"course": "Computer Science",
"grade": 88,
}
print(student["name"]) # Anna
print(student["grade"]) # 88
Reading, adding and changing values
student["email"] = "[email protected]" # add a new key
student["grade"] = 92 # change an existing value
print(student.get("age")) # 21
print(student.get("phone")) # None (no error if the key is missing)
print(student.get("phone", "unknown")) # unknown (or give a default)
Reading a missing key with square brackets, as in student["phone"], raises a KeyError. Using .get() is the safe option when a key might not exist.
Looping over a dictionary
for key, value in student.items():
print(key, "->", value)
name -> Anna
age -> 21
course -> Computer Science
grade -> 92
email -> [email protected]
Notice that grade kept its original position when we updated it, while the new email key was added at the end.
Dictionary keys must be immutable (strings, numbers or tuples work, lists don’t) and unique. Since Python 3.7, a dictionary also remembers the order in which you added items.
Combining structures: a list of dictionaries
Real data is often a list of dictionaries, one per row, just like a spreadsheet or a database table:
students = [
{"name": "Anna", "marks": 88},
{"name": "Ben", "marks": 72},
{"name": "Carla", "marks": 95},
]
total_marks = 0
for record in students:
total_marks += record["marks"]
print(total_marks) # 255
print(total_marks / len(students)) # 85.0 (the average)
Here, the list stores multiple records, while each dictionary stores information about one book.
This is a common way to represent structured data in Python.
Mutable vs immutable
One of the biggest differences between these data structures is whether they are mutable or immutable.
Mutable
A mutable object can be changed after it is created.
- List → mutable
- Set → mutable
- Dictionary → mutable
For example:
books = ["The Bell Jar", "Pachinko"]
books[0] = "Norwegian Wood"
The list itself has been changed.
Immutable
An immutable object cannot be changed in place after it is created.
- Tuple → immutable
For example:
books = ("The Bell Jar", "Pachinko")
You can’t replace one of its items like you can with a list.
One small technical note: mutability and hashability aren’t exactly the same thing. For example, dictionary keys must be hashable, not simply “immutable.” Many immutable built-in objects are hashable, but the two concepts shouldn’t be treated as identical.
Which one should I use?
When you’re deciding, ask these questions in order:
- Do I need to look things up by a name or label? Use a dictionary.
- Do I only care about unique items, or about comparing groups? Use a set.
- Is it a fixed group of values that shouldn’t change? Use a tuple.
- Otherwise, is it an ordered collection I’ll add to, remove from or sort? Use a list.
If you’re unsure, start with a list. It’s the most flexible, and you can always convert later with list(), set() or tuple().
Key takeaways
- A data structure holds many values together; Python’s four core ones are list, tuple, set and dictionary.
- Lists are ordered and changeable, and indexing starts at 0.
- Tuples are ordered but fixed. Use them for data that shouldn’t change.
- Sets hold unique items only, and are great for removing duplicates and comparing groups.
- Dictionaries store key-value pairs for lookup by name, and
.get()avoids errors on missing keys. - A list of dictionaries is a common way to represent table-like data.
- Mutable structures can be changed after creation. Immutable ones can’t.
- The brackets you use matter because they help Python determine which structure you’re creating.
Once you become comfortable with these four structures and their syntax, these concepts become much less intimidating.
✦ Thank you for reading! ✦