Python Tutorials

Python Data Structures: Lists, Sets, Tuples, and Dictionaries

When you begin learning Python, you start with simple variables—values such as 5, True, or "hello". Those single-value variables are essential, but most programs need to store and manipulate collections of related items. This is where Python Data Structures: Lists, Sets, Tuples, and Dictionaries become important. Python’s built-in data structures make this easy and expressive: they provide different ways to group values, each with its own behavior, performance traits, and best-use scenarios.

In this tutorial you will explore four core data structures and learn not only how to create and use them, but also why you would choose one over another in real code:

  • Lists— an ordered, mutable collection designed for general-purpose sequences.
  • Sets — an unordered collection of unique elements, useful for membership tests and deduplication.
  • Tuples — an ordered, immutable collection, efficient when values should never change.
  • Dictionary (dict) — a mapping from keys to values, perfect for fast lookups by meaningful names.

Each section below explains the concept, shows idiomatic examples, and highlights practical tips you’ll want to remember when writing production-quality Python.

[ Data structures overview / diagram]

Why Data Structures Matter

Think about a simple app that tracks user scores, a list of product names, or configuration options. If you tried to keep each value in a standalone variable like score1, score2, score3, your code would become unwieldy as the data grows. Data structures let you group related values into single variables and operate on them collectively. That reduces repetition, clarifies intent, and makes it possible to write algorithms that scale.

Beyond convenience, the choice of data structure affects correctness and performance. For example, lists preserve order and allow duplicates; sets enforce uniqueness and provide fast membership checks; dictionaries provide instant access by key. Choosing the right structure helps your code be both simpler and faster.

Lists (Ordered and Mutable)

Lists are the most flexible, general-purpose sequence in Python. They keep items in a defined order and allow you to add, remove, or change elements in place. Because of this mutability, lists are great for tasks where the collection changes over time—for example, accumulating results, building menus, or buffering events.

Creating lists

An empty list is written with square brackets:

my_list = []
print(my_list)  # []

You can also initialize a list with values:

numbers = [10, 20, 30, 40]
print(numbers)  # [10, 20, 30, 40]

Lists can hold any combination of Python objects; however, in production code you usually keep them homogeneous (all strings, or all integers) because it makes processing predictable.

Nested lists and len()

Lists can contain other lists (a common pattern for matrices or grouped data):

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

len(matrix) reports the number of top-level items—in this case 3—not the total number of inner values. That distinction is important when traversing nested structures.

Modifying lists

Because lists are mutable, you can change them with methods like append(), extend(), insert(), and pop():

fruits = ["apple", "banana"]
fruits.append("cherry")    # ['apple', 'banana', 'cherry']
fruits.insert(1, "orange") # ['apple', 'orange', 'banana', 'cherry']

Use these operations when you expect the collection to grow or be reordered during program execution.

[Example showing list creation and append operations]

Sets (Unique and Unordered)

A set stores unique elements without preserving order. Internally a set uses a hash table, which makes membership checks (x in my_set) very fast—often much faster than searching a list.

Sets are ideal for operations where uniqueness matters: removing duplicate items, computing mathematical set operations (union, intersection, difference), or quickly testing whether a value is present.

Creating and inspecting sets

s = {1, 2, 3, 4}
print(type(s))  # <class 'set'>
print(len(s))   # 4

If you supply duplicate values, the set automatically keeps only one copy:

s = {1, 1, 2, 2}
print(s)       # {1, 2}
print(len(s))  # 2

Ordering and equality

Because sets are unordered, two sets with the same elements are equal regardless of the order they were written in:

{1, 2} == {2, 1}  # True

However, if you need to preserve order, do not use a set; use a list or (in newer Python versions) a specialized ordered set implementation.

Demonstration of set uniqueness and membership tests]

Tuples (Ordered and Immutable)

Tuples look like lists on the surface—they preserve order and support indexing—but tuples are immutable. Once created, a tuple cannot be changed. This property makes tuples suitable for fixed collections of values, such as the coordinates of a point, or a record with a fixed structure.

Creating and using tuples

point = (10, 20)
print(point[0])  # 10
print(len(point))  # 2

Because tuples cannot be modified, operations such as append() are not available. Attempting to mutate a tuple raises an AttributeError.

When to prefer tuples

Use tuples when the structure is logically fixed—items that represent a single concept and should not be changed. There’s also a memory advantage: Python can store tuples more compactly than lists because it doesn’t need to account for future growth. In data-heavy applications (for example, storing many (x, y) pairs), this efficiency can be valuable.

[ Tuple example with attempted mutation causing an error]

Dictionaries (Key → Value Mapping)

A dictionary stores mappings from keys to values and is one of the most powerful built-in types in Python. Instead of accessing items by numeric index (like list[0]), you access values by descriptive keys (person["age"]). Dictionaries are the natural choice when you want to model records, settings, or lookups.

Building dictionaries

glossary = {
    "apple": "a red fruit",
    "bear": "a large mammal"
}
print(glossary["apple"])  # 'a red fruit'

Keys must be unique within a dictionary; assigning a value to an existing key replaces the previous value. This behavior is useful for accumulating or updating information, but be mindful when loading data from multiple sources to avoid unintentionally overwriting keys.

Practical use cases

Dictionaries are ideal for:

  • configuration objects (e.g., {"host": "localhost", "port": 8080}),
  • counting frequencies (e.g., word -> count),
  • mapping identifiers to complex objects (user id → user profile).

Because dictionary lookups are very fast, they’re frequently the correct choice when you need quick access to values based on a label rather than a position.

[Screenshot Placeholder: Dictionary example and key replacement illustration]

Which One Should You Use?

Choosing the right data structure depends on the problem you’re solving. The table below summarizes the main trade-offs and typical usage patterns.

  • List: preserves order, allows duplicates, supports modification. Use lists for ordered collections that change over time.
  • Set: enforces uniqueness, unordered, fast membership checks. Use sets where duplicates are unwanted and order is irrelevant.
  • Tuple: preserves order, immutable. Use tuples for fixed-size records and when memory efficiency matters.
  • Dictionary: key → value mapping, fast lookups by key. Use dictionaries when you need labeled access to values.

Each structure has its niche; as you gain experience your intuition about which to pick will grow. When performance matters, profile with real data since differences can be subtle.

Practice

Try these exercises to solidify your understanding. Write small scripts for each and run them to confirm the output:

  1. Create a list of five numbers, append two more numbers, then print the list and its length. Notice how len() changes after append().
  2. Create a set containing repeated values, for example {1, 1, 2, 2, 3}. Print the set and explain why duplicates vanish.
  3. Create a tuple ("Jan", "Feb", "Mar"). Attempt to assign a new value to the first element and observe the error. Then discuss why immutability might be helpful in your program.
  4. Build a small dictionary that serves as a glossary, such as {"CPU": "central processing unit", "RAM": "random access memory"}, and print one of the values by key.

[ Exercise outputs]

What’s Next?

Now that you understand lists, sets, tuples, and dictionaries, practice using them in combination—loop over a list of dictionaries, use a set to deduplicate input, or map tuples to values in a dictionary. These patterns appear throughout real-world Python code: data processing, web services, and automation scripts.

In subsequent lessons we’ll apply these structures to common tasks: sorting and filtering lists, counting with dictionaries, set operations for analytics, and using tuples as lightweight records. With deliberate practice, these tools will become second nature.

Leave a Comment