Skip to Content
Python for Beginners: Write Code That Actually Runs, Then Make It Better
Beginner
0 likes
Courses
Python for Beginners: Write Code That Actually Runs, Then Make It Better

Python Lists and Dictionaries

Store groups of values in lists and labelled values in dictionaries, then slice, check and loop over them. By the end, you can work with a list of dictionaries, which is how a lot of real data looks.

Course content

Sign in to save your progress.

Course Home

Python Lists and Dictionaries

Variables hold one value. Real data comes in groups: a list of customers, a set of prices, a product with a name, a price, and a stock count. Lists and dictionaries are how Python holds groups. You will use them in almost every program you write.

Skip ahead: If you know indexing, append(), looping over a dictionary with .items(), and .get(), continue to the quiz for this section.

Why this matters

Picking the right structure makes the rest of the code simple. Picking the wrong one makes it a fight. The short version: use a list when order matters and items are the same kind of thing. Use a dictionary when you look things up by a name or key.

Lists

fruits = ["apple", "banana", "mango"]

print(fruits[0])      # apple   (first item, counting starts at 0)
print(fruits[-1])     # mango   (last item)
print(len(fruits))    # 3

fruits.append("papaya")     # add to the end
fruits[1] = "orange"        # replace an item
fruits.remove("apple")      # remove by value
print(fruits)               # ['orange', 'mango', 'papaya']

Counting starts at 0. The first item is [0], not [1]. Negative numbers count from the end, so [-1] is the last item. Asking for a position that does not exist gives an IndexError.

Slicing and checking

numbers = [10, 20, 30, 40, 50]
print(numbers[1:3])     # [20, 30]  from index 1, stop before 3
print(numbers[:2])      # [10, 20]
print(30 in numbers)    # True
print(sorted([3, 1, 2]))  # [1, 2, 3]

Dictionaries

A dictionary stores pairs: a key and its value. You look things up by key, not by position.

product = {
    "name": "Notebook",
    "price": 45.0,
    "stock": 120,
}

print(product["name"])        # Notebook
product["stock"] = 115        # update a value
product["color"] = "blue"     # add a new key
print(product)

⚠ Warning: Asking for a key that does not exist, like product["weight"], raises a KeyError and stops your program. When a key might be missing, use product.get("weight"), which returns None, or product.get("weight", 0) to choose your own default.

product = {"name": "Notebook", "price": 45.0}
print(product.get("weight"))       # None
print(product.get("weight", 0))    # 0

Looping over them

stock = {"apple": 30, "banana": 0, "mango": 12}

for fruit, count in stock.items():
    if count == 0:
        print(f"{fruit}: out of stock")
    else:
        print(f"{fruit}: {count} left")

.items() gives you each key and value together. Looping over the dictionary directly gives you only the keys.

A real-world example: a list of dictionaries

This is the shape of most real data you will meet, from spreadsheets, APIs, and databases: a list where each item is a dictionary.

orders = [
    {"customer": "Ana", "total": 1250.0, "paid": True},
    {"customer": "Ben", "total": 480.0, "paid": False},
    {"customer": "Carla", "total": 900.0, "paid": False},
]

unpaid_total = 0
for order in orders:
    if not order["paid"]:
        print(f"Reminder for {order['customer']}: {order['total']:.2f}")
        unpaid_total += order["total"]

print(f"Total unpaid: {unpaid_total:.2f}")   # 1380.00

Notice the single quotes inside the f-string: order['customer']. The f-string already uses double quotes, so the key uses single ones. Mixing them up is a common source of syntax errors.

Common mistakes

  • Starting at 1. items[1] is the second item.
  • Using a list where you need lookups. Searching a list of pairs for a name every time is slow and messy. That is what a dictionary is for.
  • Assuming a key exists. Use .get() for data you did not create yourself.
  • Copying by assignment. b = a does not copy a list. Both names point to the same list. Use b = a.copy() if you need a separate one.

💡 Tip: When you get data and do not know its shape, print it with print(type(data)) and look at one item first. Half the battle is knowing whether you are holding a list, a dictionary, or a list of dictionaries.

What happens if you skip this step

You end up with variables named customer1, customer2, customer3, and a program that breaks when customer 4 shows up. Lists and dictionaries are not an advanced topic. They are the normal way to hold real data. Everything after this, including reading files and talking to APIs, assumes you know them.

Quick check: in the orders example, how would you print only the names of customers who have paid?

About

Store groups of values in lists and labelled values in dictionaries, then slice, check and loop over them. By the end, you can work with a list of dictionaries, which is how a lot of real data looks.

Duration
5 min
Last update
09/05/2026
Was this helpful?
​ 0 ​ 0

Comments (0)

Sign in to comment

No comments yet.