Skip to content
Python Lists & Dicts Explained — Complete Guide with Examples

Python Lists & Dicts Explained — Complete Guide with Examples

DodaTech Updated Jun 4, 2026 10 min read

Real programs work with collections of data — a list of usernames, a dictionary of product prices, a set of unique IP addresses. Python gives you four built-in collection types, each designed for a different job.

What You’ll Learn

  • When to use lists vs tuples vs dicts vs sets
  • How to create, access, modify, and iterate over each collection type
  • List comprehensions — write cleaner loops in one line
  • Slicing, zip, enumerate, and other practical patterns
  • Common mistakes that waste hours of debugging time

Why Collections Matter

Without collections, you’d need a separate variable for every piece of data — user1, user2, user3 — which is impractical for real software. Durga Antivirus Pro stores threat signatures in dictionaries (mapping file hashes to threat names) and maintains watchlists as sets (no duplicates). DodaZIP processes lists of file paths. Doda Browser uses sets to track unique visited URLs. Collections are the backbone of data management in every application.

    flowchart LR
    A["Python Basics"] --> B["Control Flow"]
    B --> C["Functions"]
    C --> D["Lists & Dicts"]
    D --> E["Modules & Packages"]
    E --> F["File I/O & Errors"]
    A:::done --> B:::done --> C:::done --> D:::current --> E
    style A fill:#2563eb,stroke:#2563eb,color:#fff
    style B fill:#2563eb,stroke:#2563eb,color:#fff
    style C fill:#2563eb,stroke:#2563eb,color:#fff
    style D fill:#2563eb,stroke:#2563eb,color:#fff
    style E fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style F fill:#f1f5f9,stroke:#94a3b8,color:#64748b
  
Prerequisite: You should understand variables, data types, and for loops. If those are new, review https://tutorials.dodatech.com/programming-languages/python/py-basics/ and https://tutorials.dodatech.com/programming-languages/python/py-control-flow/ first.
    mindmap
  root((Python Collections))
    List
      Ordered
      Mutable
      Allows duplicates
      `[1, 2, 3]`
    Tuple
      Ordered
      Immutable
      Allows duplicates
      `(1, 2, 3)`
    Dict
      Key-value pairs
      Mutable
      Unique keys
      `{"a": 1}`
    Set
      Unordered
      Mutable
      Unique items
      `{1, 2, 3}`
  

Lists

Think of a list as a shopping list — an ordered collection where you can add, remove, or change items. The order matters (eggs are first, milk is second), and duplicates are allowed (buying two cartons of milk).

# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# Access items (zero-indexed)
print(fruits[0])     # "apple" — first item
print(fruits[-1])    # "cherry" — last item (negative index = from end)
print(fruits[1:3])   # ["banana", "cherry"] — slicing [start:end]

# Modify
fruits[1] = "blueberry"        # Change existing item
fruits.append("date")          # Add to end
fruits.insert(0, "apricot")    # Add at specific position
removed = fruits.pop()         # Remove and return last item

Common List Methods

nums = [3, 1, 4, 1, 5, 9]

len(nums)           # 6 — number of items
nums.count(1)       # 2 — how many 1s
nums.index(4)       # 2 — first position of 4
nums.sort()         # [1, 1, 3, 4, 5, 9] — sorts in-place
nums.reverse()      # [9, 5, 4, 3, 1, 1] — reverses in-place
sorted(nums)        # returns new sorted list (original unchanged)

Iterating Over Lists

for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# Check membership
if "apple" in fruits:
    print("Found it!")

Tuples

A tuple is like a list that’s frozen — once created, it cannot change. Use tuples for data that shouldn’t be modified, like coordinates or configuration constants.

point = (10, 20)
x, y = point           # unpacking
print(x, y)            # 10 20

# Single-element tuple needs trailing comma
single = (42,)

# Tuples are faster and safer when data shouldn't change
colors = ("red", "green", "blue")
# colors[0] = "pink"   # TypeError! — can't modify a tuple

Tuples are often used for returning multiple values from a function and as dictionary keys (lists can’t be keys because they’re mutable).

Dicts

A dict is like a real dictionary — you look up a word (key) to find its definition (value). Instead of numeric indices, you use meaningful keys.

# Creating a dict
person = {
    "name": "Alice",
    "age": 25,
    "role": "Developer"
}

# Access values
print(person["name"])               # "Alice" — error if key missing
print(person.get("age"))            # 25 — safe, returns None if missing
print(person.get("salary", 0))      # 0 — default value if missing

# Modify
person["age"] = 26
person["email"] = "alice@example.com"  # Add new key-value pair
del person["role"]                     # Remove a key

# Check
if "name" in person:
    print("Has name")

Dict Methods

for key in person:                  # Iterate keys
    print(key)

for key, value in person.items():   # Iterate key-value pairs
    print(f"{key}: {value}")

for value in person.values():       # Iterate values
    print(value)

Dict Comprehension

squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets

A set is like a bag of unique items — duplicates are automatically removed. Think of it as a guest list where no name appears twice.

unique = {1, 2, 3, 3, 2, 1}
print(unique)  # {1, 2, 3}

# Remove duplicates from a list
items = [1, 2, 2, 3, 3, 3]
deduped = list(set(items))  # [1, 2, 3]

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)  # union: {1, 2, 3, 4, 5, 6}
print(a & b)  # intersection: {3, 4}
print(a - b)  # difference: {1, 2}

List Comprehensions

A list comprehension is a compact way to create lists. Instead of writing a for-loop with several lines, you write one line that says “make a list where each element is X for each item in Y.”

# Traditional way
squares = []
for x in range(10):
    squares.append(x ** 2)

# Comprehension — cleaner and faster
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

With Condition

evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Zip Two Lists

names = ["Alice", "Bob", "Charlie"]
grades = [85, 92, 78]
students = {name: grade for name, grade in zip(names, grades)}
# {'Alice': 85, 'Bob': 92, 'Charlie': 78}

Common Mistakes

1. Confusing sort() and sorted()

nums = [3, 1, 2]
result = nums.sort()  # Returns None! Modifies nums in-place
print(result)         # None

Fix: Use sorted(nums) when you need a new sorted list. Use nums.sort() only when modifying the original.

2. Modifying a List While Iterating

nums = [1, 2, 3, 4, 5]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)  # Skips elements!

Fix: Iterate over a copy: for n in nums[:]: or build a new list with a comprehension.

3. Using a Mutable Type as Dict Key

d = {}
d[[1, 2]] = "value"  # TypeError: unhashable type: 'list'

Fix: Use tuples instead: d[(1, 2)] = "value".

4. Forgetting Trailing Comma in Single-Element Tuples

t = (42)
print(type(t))  # <class 'int'> — not a tuple!

Fix: Add a trailing comma: t = (42,).

5. Expecting Dicts to Maintain Order on Old Python

Since Python 3.7, dicts preserve insertion order. But code relying on this won’t work on Python 3.6 or earlier.

6. Using = Instead of == in Comprehensions

# SyntaxError!
evens = [x for x in range(10) if x = 2]

Fix: Use == for comparison.

Practice Questions

1. What’s the output of [1, 2, 3] + [4, 5]?

[1, 2, 3, 4, 5]. The + operator concatenates lists.

2. Why does tuple([1, 2, 3]) work but list((1, 2, 3)) also works?

Both are type conversions. tuple() converts a list to a tuple. list() converts a tuple to a list.

3. What’s wrong with this code?

d = {}
d["key"] = "value"
print(d["missing"])

KeyError because “missing” doesn’t exist as a key. Use d.get("missing") to avoid the error.

4. How do you remove duplicates from a list?

list(set([1, 2, 2, 3, 3, 3]))[1, 2, 3]. But note: sets are unordered, so the original order is lost.

Challenge: Write a function word_count(text) that returns a dictionary mapping each word to how many times it appears. Ignore case and punctuation.

Solution
def word_count(text: str) -> dict:
    words = text.lower().replace(",", "").replace(".", "").split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts

print(word_count("Hello world! Hello Python, hello everyone."))
# {'hello': 3, 'world': 1, 'python': 1, 'everyone': 1}

FAQ

What's the difference between a list and a tuple?
Lists are mutable (can add/remove/change items). Tuples are immutable (fixed after creation). Use lists for data that changes, tuples for data that shouldn’t.
When should I use a dict vs a list?
Use a dict when you need to look up values by a meaningful key (name → grade). Use a list when you need ordered items accessed by position (index 0, 1, 2…).
Why does removing items from a list while iterating skip elements?
Because removing shifts remaining elements down, but the loop index keeps advancing. Iterate over a copy (list[:]) or use a list comprehension instead.
Can I use a list as a dict key?
No — lists are unhashable because they’re mutable. Use a tuple instead if you need a compound key.
What's the difference between sort() and sorted()?
list.sort() sorts in-place and returns None. sorted(list) returns a new sorted list and leaves the original untouched.

Try It Yourself

Run this to see collections in action:

# List comprehensions in action
numbers = [1, 2, 3, 4, 5, 6]
squares = [x ** 2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]

print(f"Original: {numbers}")
print(f"Squares: {squares}")
print(f"Evens: {evens}")

# Dict comprehension
squared_dict = {x: x ** 2 for x in range(5)}
print(f"Squared dict: {squared_dict}")

# Zip two lists
names = ["Alice", "Bob", "Charlie"]
grades = [85, 92, 78]
students = {name: grade for name, grade in zip(names, grades)}
print(f"Students: {students}")

Expected output:

Original: [1, 2, 3, 4, 5, 6]
Squares: [1, 4, 9, 16, 25, 36]
Evens: [2, 4, 6]
Squared dict: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Students: {'Alice': 85, 'Bob': 92, 'Charlie': 78}

Mini Project: Student Grade Tracker

Build a grade tracker using dicts and lists:

grades = {}

def add_student(name: str) -> None:
    if name not in grades:
        grades[name] = []
        print(f"Added student: {name}")
    else:
        print(f"{name} already exists!")

def add_grade(name: str, grade: float) -> None:
    if name in grades:
        grades[name].append(grade)
        print(f"Added {grade} for {name}")
    else:
        print(f"Student {name} not found!")

def average(name: str) -> float:
    if name not in grades or not grades[name]:
        return 0.0
    return sum(grades[name]) / len(grades[name])

def report() -> None:
    print("\n=== CLASS REPORT ===")
    print(f"{'Student':<12} {'Avg Grade':<10} {'Grades'}")
    print("-" * 50)
    for student, grade_list in sorted(grades.items(),
                                       key=lambda s: average(s[0]),
                                       reverse=True):
        avg = average(student)
        print(f"{student:<12} {avg:<10.1f} {grade_list}")
    print("=" * 50)

# Try it out
add_student("Alice")
add_student("Bob")
add_student("Charlie")
add_grade("Alice", 85)
add_grade("Alice", 92)
add_grade("Alice", 78)
add_grade("Bob", 90)
add_grade("Bob", 88)
add_grade("Charlie", 95)
add_grade("Charlie", 100)
report()

Expected output:

Added student: Alice
Added student: Bob
Added student: Charlie
Added 85 for Alice
Added 92 for Alice
Added 78 for Alice
Added 90 for Bob
Added 88 for Bob
Added 95 for Charlie
Added 100 for Charlie

=== CLASS REPORT ===
Student      Avg Grade  Grades
--------------------------------------------------
Charlie      97.5       [95, 100]
Bob          89.0       [90, 88]
Alice        85.0       [85, 92, 78]
==================================================

What’s Next

Now master collections and move on to organizing code with modules and packages.

TopicDescriptionLink
Python Modules & PackagesOrganize and reuse codehttps://tutorials.dodatech.com/programming-languages/python/py-modules/
Python File I/ORead, write, and handle errorshttps://tutorials.dodatech.com/programming-languages/python/py-io/
SQL DatabasesStore collections persistentlySQL

Practice tip: Extend the grade tracker with a passing_grade(threshold) function that returns students above a threshold, and a class_average() that averages all students together.

What’s Next

Congratulations on completing this Py Lists Dicts tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro