Scrollable Nav Bar

Python Data Structures

When you first learn Python, you usually start with simple variables that hold a single value—like 5, True, or "hello". That’s a great start, but real programs almost always need to work with collections of values.

That’s where data structures come in. In this tutorial, you’ll learn four of the most important built-in Python data structures:

  • List: an ordered, changeable collection
  • Set: an unordered collection of unique values
  • Tuple: an ordered, unchangeable collection
  • Dictionary (dict): a key → value mapping

Along the way, you’ll see practical examples, learn how each structure behaves, and understand when to use which one.

[Data structures overview / diagram]


1. Why Data Structures Matter

Imagine you’re building a small app that stores:

  • multiple user scores,
  • a list of names,
  • a set of unique tags,
  • or a mapping of words to meanings.

If you try to store everything in separate variables like score1, score2, score3, you’ll quickly run into messy code. Data structures let you keep related items together in a single variable, making your code cleaner, more scalable, and easier to maintain.


2. Lists (Ordered and Mutable)

A list is the most commonly used collection in Python. It can store multiple values in a single variable, and you can modify it (add, remove, update values).

2.1 Create an empty list

my_list = []
print(my_list)
Code language: PHP (php)

This creates an empty list.

[ Empty list output in Python]

2.2 Create a list with values

my_list = [10, 20, 30, 40]
print(my_list)
Code language: PHP (php)

This list has 4 elements.

2.3 Lists can store any type

Lists can store strings:

names = ["Alice", "Bob", "Charlie"]
print(names)
Code language: PHP (php)

They can also store mixed types:

mixed = ["Python", 100, True, 3.14]
print(mixed)
Code language: PHP (php)

Python allows this flexibility, but in real projects you’ll often keep lists consistent (e.g., a list of numbers or a list of strings) for clarity.

2.4 Lists can contain other lists (nested lists)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix)
Code language: PHP (php)

This is called a list of lists. Each inner list is its own list.

[ Nested list output]

2.5 Length of a list: len()

Use len() to get how many elements are in a list:

numbers = [10, 20, 30, 40]
print(len(numbers))  # 4
Code language: PHP (php)

Important detail: for a list of lists, len() counts only the outer elements.

list_of_lists = [[1, 2], [3, 4], [5, 6]]
print(len(list_of_lists))  # 3
Code language: PHP (php)

Even though each inner list has values, the outer list contains three items, so the length is 3.

2.6 Adding items to a list: append()

Lists are mutable, which means you can change them after creating them.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # [1, 2, 3, 4]
Code language: PHP (php)

You can keep appending:

my_list.append(6)
print(my_list)  # [1, 2, 3, 4, 6]
Code language: CSS (css)

3. Sets (Unique and Unordered)

A set is similar to a list, but it has two major differences:

  1. Every element must be unique (no duplicates)
  2. Order does not matter

3.1 Create a set

Sets use curly braces {}:

my_set = {1, 2, 3, 4, 5}
print(my_set)
Code language: PHP (php)

You can check its type:

print(type(my_set))
Code language: PHP (php)

And you can check its size:

print(len(my_set))
Code language: PHP (php)

[ Printing a set and its type]

3.2 Sets automatically remove duplicates

my_set = {1, 1, 1, 2, 2}
print(my_set)       # {1, 2}
print(len(my_set))  # 2
Code language: PHP (php)

Even if you try to add duplicates, the set keeps only one copy.

3.3 Set equality ignores order

Lists care about order:

print([1, 2] == [1, 2])  # True
print([1, 2] == [2, 1])  # False
Code language: PHP (php)

Sets do not care about order:

print({1, 2} == {2, 1})  # True
Code language: PHP (php)

Even if you write elements in a different order, it still represents the same set.


4. Tuples (Ordered and Immutable)

A tuple is like a list in the sense that it stores items in order, but the biggest difference is:

Tuples cannot be changed after creation (they are immutable).

4.1 Create a tuple

Tuples use parentheses ():

my_tuple = (1, 2, 3)
print(my_tuple)
print(len(my_tuple))  # 3
Code language: PHP (php)

4.2 Tuple equality depends on order

print((1, 2) == (1, 2))  # True
print((1, 2) == (2, 1))  # False
Code language: PHP (php)

4.3 You cannot append to a tuple

This works with lists:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
Code language: PHP (php)

But tuples don’t support append():

my_tuple = (1, 2, 3)
# my_tuple.append(4)  # AttributeError
Code language: PHP (php)

If you try, Python raises an error because tuples are not meant to be modified.

[ Tuple append error message]

4.4 Why use tuples at all?

If tuples are less flexible, why do programmers use them?

One big reason is efficiency. Because Python knows a tuple won’t grow or shrink, it can store it more compactly in memory compared to a list.

A very common real-world use case is storing fixed pairs like coordinates:

point = (10, 20)  # (x, y)
Code language: PHP (php)

If your program stores thousands or millions of coordinate pairs, tuples can be a good choice.


5. Dictionaries (Key → Value Mapping)

A dictionary (also called dict) stores values in key-value pairs.

Think of it like a real dictionary:

  • You look up a word (the key)
  • You get its meaning (the value)

5.1 Create a dictionary

Dictionaries also use curly braces {}, but inside they contain key-value pairs separated by colons :.

my_dict = {
    "apple": "a red fruit",
    "bear": "a scary animal"
}

print(my_dict)
Code language: PHP (php)

[ Dictionary printed output]

5.2 Access values using keys

print(my_dict["apple"])  # a red fruit
Code language: PHP (php)

Here:

  • "apple" is the key
  • "a red fruit" is the value

5.3 Keys must be unique

If you assign the same key again, the new value replaces the old one.

my_dict = {
    "apple": "a red fruit",
    "apple": "sometimes a green fruit"
}

print(my_dict["apple"])  # sometimes a green fruit
Code language: PHP (php)

This replacement behavior is important to remember when working with dictionaries.

5.4 Order and dictionaries

In dictionaries, you don’t use “position” like in lists or tuples. You always access values by key.

This makes dictionaries perfect for problems like:

  • user profile fields ({"name": "...", "age": ...})
  • configuration settings
  • word counts and frequency maps
  • fast lookups by identifier

6. Quick Comparison: Which One Should You Use?

Use lists when you need:

  • order matters
  • duplicates are allowed
  • you want to add/remove/change items

Use sets when you need:

  • uniqueness (no duplicates)
  • fast membership checks (“is this item present?”)
  • order doesn’t matter

Use tuples when you need:

  • fixed, unchangeable collections
  • structured “record-like” values (like (x, y))
  • memory efficiency for many small fixed groups

Use dictionaries when you need:

  • key-based lookup
  • meaningful labels for values (like "apple" → "red fruit")
  • mapping and grouping data

7. Practice: Try These Mini Exercises

  1. Create a list of 5 numbers. Append two more numbers. Print the list and its length.
  2. Create a set with repeated values like {1, 1, 2, 2, 3}. Print the set and explain what happened.
  3. Create a tuple ("Jan", "Feb", "Mar"). Try to modify one value and observe the error.
  4. Create a dictionary for a mini glossary, like {"CPU": "...", "RAM": "..."}. Print the meaning of one key.

[ Exercise outputs]


8. What’s Next?

Now that you’ve met Python’s core data structures, you’re ready to use them in real programming patterns—looping through lists, filtering sets, grouping data in dictionaries, and building structured data with tuples.

In the next lessons, you’ll use these structures repeatedly, and they’ll quickly start to feel natural.