Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Lists, Tuples, Sets, and Dictionaries

Python provides four core built-in collection types, and choosing the right one is one of the most practical skills in the language. Lists and dictionaries are mutable and extremely common for everyday data manipulation; tuples are immutable and useful for fixed groupings of values; sets are unordered collections optimized for membership testing and eliminating duplicates.

Understanding exactly which of these types can be changed after creation — and which cannot — prevents an entire category of bugs, especially when a collection is passed around and modified in multiple places in a program.

Why it matters

Almost all data in a Python program sits in one of these four structures, and data from files, databases and APIs arrives as lists and dictionaries. Choosing between them is the first design decision in most functions, and each choice has consequences for what the code can do and how fast it runs.

Lists — Ordered and Mutable

A list is an ordered, mutable collection written with square brackets, e.g. [1, 2, 3]. You can add, remove, or change elements after creation using methods like append(), remove(), insert(), and pop(), or by assigning directly to an index. Lists can hold mixed types and can be nested inside one another.

Tuples — Ordered and Immutable

A tuple is an ordered, immutable collection written with parentheses, e.g. (1, 2, 3). Once created, a tuple's contents cannot be changed, added to, or removed — attempting to do so raises a TypeError. Tuples are commonly used for fixed groupings of related values (like coordinates) and as dictionary keys, since they are hashable as long as their contents are hashable, unlike lists.

Sets — Unordered and Unique

A set is an unordered collection of unique, hashable elements, written with curly braces, e.g. {1, 2, 3}, or created from another iterable with set(). Sets automatically discard duplicates and support fast membership testing (x in my_set) and mathematical set operations like union (|), intersection (&), and difference (-). Sets are mutable, but their elements must themselves be immutable/hashable.

Dictionaries — Key-Value Pairs

A dictionary maps unique keys to values, written with curly braces containing key: value pairs, e.g. {"name": "Alice", "age": 30}. Dictionaries are mutable — you can add, update, or delete key-value pairs after creation — and since Python 3.7, they preserve insertion order. Values are accessed by key rather than by numeric position: my_dict["name"] rather than my_dict[0].

Indexing and Slicing

Lists and tuples (both ordered sequences) support indexing with square brackets, where index 0 is the first element and -1 is the last. Slicing with the syntax [start:stop:step] extracts a sub-sequence without modifying the original — start is inclusive, stop is exclusive, and step controls the interval (a negative step reverses direction). Sets and dictionaries, being unordered by concept, do not support indexing or slicing.

Examples

Mutability differences between a list and a tuple

Python
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] = "avocado"
print(fruits)

coordinates = (10, 20)
try:
    coordinates[0] = 99
except TypeError as e:
    print("Error:", e)
Output
['avocado', 'banana', 'cherry', 'date']
Error: 'tuple' object does not support item assignment

Sets for uniqueness, dictionaries for key-based lookup, and slicing

Python
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = set(numbers)
print(unique_numbers)

person = {"name": "Sam", "age": 25}
person["city"] = "Austin"
print(person)

letters = ["a", "b", "c", "d", "e"]
print(letters[1:4])
print(letters[::-1])
Output
{1, 2, 3, 4}
{'name': 'Sam', 'age': 25, 'city': 'Austin'}
['b', 'c', 'd']
['e', 'd', 'c', 'b', 'a']

Common Mistakes

  • Trying to modify a tuple in place (e.g. my_tuple[0] = 5), forgetting that tuples are immutable and raise a TypeError.
  • Assuming a set preserves insertion order or supports indexing — sets are unordered and do not support my_set[0].
  • Accessing a dictionary key that does not exist with square brackets and getting a KeyError, instead of using .get(key, default) for a safe lookup.
  • Confusing slice bounds — forgetting that the stop index in a slice is exclusive, so letters[1:4] returns indices 1, 2, and 3, not 4.

Exercise

From the list of purchases, print the distinct items in alphabetical order, and then a dictionary that counts how many times each item was bought.

Expected output: ['bag', 'book', 'pen'] then {'pen': 3, 'book': 2, 'bag': 1}

Python · starter code
purchases = ["pen", "book", "pen", "bag", "book", "pen"]

# TODO: print the distinct items, sorted

# TODO: build a dictionary of item -> count, and print it
Show hints
  • set(purchases) removes duplicates, and sorted(...) returns a sorted list.
  • counts.get(item, 0) + 1 gives the new count, whether or not the item has been seen before.
Show solution
Python · solution
purchases = ["pen", "book", "pen", "bag", "book", "pen"]

print(sorted(set(purchases)))

counts = {}
for item in purchases:
    counts[item] = counts.get(item, 0) + 1
print(counts)

Quick quiz

1. Which of these structures cannot be changed after it is created?

  • A. list
  • B. tuple
  • C. set
  • D. dict
Show answer

B. A tuple is immutable. The other three can be changed in place.

2. Which structure automatically removes duplicate values?

  • A. list
  • B. tuple
  • C. set
  • D. dict values
Show answer

C. A set holds each value at most once.

3. Which structure is designed for looking up a value by a name or an id?

  • A. list
  • B. tuple
  • C. set
  • D. dict
Show answer

D. A dictionary maps keys to values and finds a key without scanning.

Interview questions

What is the difference between a list and a tuple?

Show answer

Both are ordered sequences that allow duplicates and indexing. A list is mutable: items can be added, removed and replaced. A tuple is immutable: once created it cannot change. Because of that a tuple can be used as a dictionary key or a set element, and it signals that the data is a fixed record, such as a pair of coordinates.

When would you use a set instead of a list?

Show answer

When only membership matters and duplicates are not wanted. Testing x in a_set takes roughly the same time whatever the size of the set, while x in a_list checks the items one by one. Sets also provide union, intersection and difference. A set has no order and cannot be indexed, and its elements must be hashable.

Key Points to Remember

  • Lists ([]) are ordered and mutable; tuples (()) are ordered and immutable.
  • Sets ({}) store unique, unordered, hashable elements and support fast membership tests and set algebra.
  • Dictionaries ({key: value}) map unique keys to values and preserve insertion order since Python 3.7.
  • Indexing and slicing ([start:stop:step]) work on ordered sequences like lists, tuples, and strings, but not on sets or dictionaries.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering