← Back to course

Lists: Storing Many Values

Lists: Storing Many Values

Welcome back.

In the previous lesson, you learned loops.

Your programs learned how to repeat work with:

for
while

Very good.

Now Python can repeat tasks automatically.

It can count.

It can ask again.

It can calculate totals.

It can show menus.

Beautiful.

But now we have another problem.

What if we need to store many values?

For example:

A list of products.
A list of users.
A list of scores.
A list of cities.
A list of tasks.
A list of passwords you should not write in plain text.

Without lists, you might write:

product1 = "Keyboard"
product2 = "Mouse"
product3 = "Notebook"

This works.

But it becomes ugly very quickly.

What if you have 100 products?

Are you going to write:

product100 = "Something"

Please no.

Python has a better way.

Lists.

Lists let you store many values in one variable.

Very useful.

Very common.

Very Python.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, your programs will be able to work with collections of data.

That is a very big step.

Because real programs almost never work with just one value.

They work with many values.

Many users.

Many products.

Many tasks.

Many problems.

Very realistic.

Very programming.

What Is a List?

A list is a collection of values.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

Here:

products

is one variable.

But it stores three values:

Keyboard
Mouse
Notebook

A list uses square brackets:

[]

Items inside the list are separated by commas:

["Keyboard", "Mouse", "Notebook"]

This is much better than writing:

product1 = "Keyboard"
product2 = "Mouse"
product3 = "Notebook"

Lists keep related values together.

Like a small box.

But digital.

And less likely to contain random cables.

Your First List

Create a file:

lists.py

Write:

products = ["Keyboard", "Mouse", "Notebook"]

print(products)

Run it:

python lists.py

or:

python3 lists.py

Output:

['Keyboard', 'Mouse', 'Notebook']

Python prints the whole list.

Notice that Python shows square brackets and quotes.

That is normal.

It is showing you the list structure.

The list is not just text.

It is a collection.

A tiny container of values.

Very organized.

Suspiciously organized.

Lists Can Store Different Types

A list can store different types of values.

Example:

mixed_list = ["Anna", 25, 19.99, True]

print(mixed_list)

Output:

['Anna', 25, 19.99, True]

This works.

But be careful.

Just because Python allows something does not mean it is always a good idea.

Often, lists are clearer when they store similar things.

Good:

prices = [10.99, 25.50, 5.00]
names = ["Anna", "Marco", "Sofia"]
scores = [90, 85, 72]

Less clear:

random_things = ["Anna", 42, True, "Pizza", 3.14]

Python allows freedom.

Freedom is nice.

Freedom can also create chaos with square brackets.

Use responsibly.

Accessing Items by Index

Each item in a list has a position.

This position is called an index.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

print(products[0])
print(products[1])
print(products[2])

Output:

Keyboard
Mouse
Notebook

Important:

The first item has index 0.

Not 1.

Python starts counting from zero.

Again.

Python and zero are still very close friends.

So:

products[0] -> Keyboard
products[1] -> Mouse
products[2] -> Notebook

This is very important.

Indexes are how you access specific list items.

Indexes Start at 0

This is one of the most common beginner surprises.

You may expect:

products[1]

to mean the first item.

But no.

In Python:

products[0]

means the first item.

Example:

cities = ["Rome", "Milan", "Naples"]

print(cities[0])

Output:

Rome

If you want the second item:

print(cities[1])

Output:

Milan

At first this feels strange.

Then it becomes normal.

Then you start counting from zero in your head.

At that point, programming has changed you.

Not necessarily for the worse.

Probably.

Getting the Last Item

You can use negative indexes.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

print(products[-1])

Output:

Notebook

-1 means:

last item

Other examples:

print(products[-2])
print(products[-3])

Output:

Mouse
Keyboard

Negative indexes count from the end.

Very useful.

Very Python.

Very “I want the last thing without counting everything”.

Python can be kind sometimes.

Updating a List Item

Lists can be changed.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

products[1] = "Gaming Mouse"

print(products)

Output:

['Keyboard', 'Gaming Mouse', 'Notebook']

We changed the item at index 1.

Before:

Mouse

After:

Gaming Mouse

Remember:

index 1 is the second item

Python does exactly what you ask.

Even if you forget indexes start at zero.

Python will not protect you from your own confidence.

Very educational.

Adding Items with append()

You can add an item to the end of a list with append().

Example:

products = ["Keyboard", "Mouse"]

products.append("Notebook")

print(products)

Output:

['Keyboard', 'Mouse', 'Notebook']

append() adds one item to the end.

This is very common.

Example with user input:

products = []

product = input("Product name: ")
products.append(product)

print(products)

If the user types:

Keyboard

Output:

['Keyboard']

An empty list starts like this:

products = []

Then you can add items later.

Very useful.

Very flexible.

Very “we are building the list as we go”.

Adding Several Items

You can call append() many times.

Example:

products = []

products.append("Keyboard")
products.append("Mouse")
products.append("Notebook")

print(products)

Output:

['Keyboard', 'Mouse', 'Notebook']

This is useful when values arrive one by one.

For example:

user input
data from a file
data from a database
data from an API

Lists are everywhere.

They are like bags for data.

But less chaotic.

Unless you put chaotic data inside.

Then it is your fault.

Probably.

Removing Items with remove()

You can remove an item by value with remove().

Example:

products = ["Keyboard", "Mouse", "Notebook"]

products.remove("Mouse")

print(products)

Output:

['Keyboard', 'Notebook']

remove() removes the first matching item.

Important:

products.remove("Mouse")

means:

Find "Mouse" and remove it.

It does not mean:

Remove item at index Mouse.

Because that would be nonsense.

Python accepts many things.

But not that.

remove() Needs an Existing Item

If you try to remove an item that does not exist, Python gives an error.

Example:

products = ["Keyboard", "Mouse"]

products.remove("Notebook")

Error:

ValueError

Why?

Because "Notebook" is not in the list.

Later, we can handle errors better.

For now, you can check first:

products = ["Keyboard", "Mouse"]

if "Notebook" in products:
    products.remove("Notebook")
else:
    print("Notebook is not in the list.")

This is safer.

The program checks before removing.

Very responsible.

Very adult.

Unlike some code written at 2 a.m.

Checking If an Item Exists

Use in to check if an item exists in a list.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

if "Mouse" in products:
    print("Mouse is available.")
else:
    print("Mouse is not available.")

Output:

Mouse is available.

You can also check the opposite with not in:

if "Monitor" not in products:
    print("Monitor is missing.")

Output:

Monitor is missing.

This is very useful.

You will use in often.

Lists and in are good friends.

Like Python and zero.

But less suspicious.

List Length with len()

len() tells you how many items are in a list.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

print(len(products))

Output:

3

This means the list has 3 items.

You can use it in messages:

products = ["Keyboard", "Mouse", "Notebook"]

print(f"We have {len(products)} products.")

Output:

We have 3 products.

len() is very useful.

It works with lists.

It also works with strings.

Example:

word = "Python"

print(len(word))

Output:

6

Python likes counting things.

Very helpful.

Very accountant energy.

Looping Through a List

Lists and loops work beautifully together.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

for product in products:
    print(product)

Output:

Keyboard
Mouse
Notebook

This means:

For each product in the products list, print the product.

This is one of the most important patterns in Python.

A list stores many values.

A loop processes them one by one.

Very powerful.

Very common.

Very “now we are programming for real”.

Better Output with Lists

You can combine loops and f-strings.

Example:

products = ["Keyboard", "Mouse", "Notebook"]

for product in products:
    print(f"Product: {product}")

Output:

Product: Keyboard
Product: Mouse
Product: Notebook

This looks cleaner.

You can also add numbering:

products = ["Keyboard", "Mouse", "Notebook"]

number = 1

for product in products:
    print(f"{number}. {product}")
    number += 1

Output:

1. Keyboard
2. Mouse
3. Notebook

This works.

But Python has an even nicer tool for numbering.

We will learn it soon.

Not now.

One dragon at a time.

Looping Through Prices

Lists can store numbers too.

Example:

prices = [10.99, 25.50, 5.00]

for price in prices:
    print(f"Price: {price:.2f}")

Output:

Price: 10.99
Price: 25.50
Price: 5.00

You can calculate a total:

prices = [10.99, 25.50, 5.00]

total = 0

for price in prices:
    total += price

print(f"Total: {total:.2f}")

Output:

Total: 41.49

This is a very common pattern:

list of numbers
loop through numbers
calculate total

Simple.

Useful.

Very real.

Many invoices begin like this.

Then taxes enter.

And the music becomes darker.

Finding the Biggest Number

You can use a loop to find the biggest number.

Example:

scores = [75, 90, 62, 88]

highest_score = scores[0]

for score in scores:
    if score > highest_score:
        highest_score = score

print(f"Highest score: {highest_score}")

Output:

Highest score: 90

What happens?

Start by assuming the first score is the highest.
Check every score.
If a score is bigger, update highest_score.
Print the final result.

This is a classic programming pattern.

Assume a starting value.

Loop.

Compare.

Update.

Very useful.

Very algorithmic.

Sounds fancy.

But it is just careful checking.

Like looking for the biggest potato in a bag.

Computer science is glamorous.

Empty Lists

An empty list has no items.

Example:

products = []

print(products)
print(len(products))

Output:

[]
0

Empty lists are useful when you want to add items later.

Example:

products = []

products.append("Keyboard")
products.append("Mouse")

print(products)

Output:

['Keyboard', 'Mouse']

Many programs start with an empty list.

Then they fill it.

This is very normal.

An empty list is not useless.

It is just waiting for data.

Like a basket.

A very patient basket.

Building a List from User Input

Create a file:

product_list.py

Write:

products = []

product_count = int(input("How many products? "))

for number in range(1, product_count + 1):
    product = input(f"Product {number}: ")
    products.append(product)

print("Your products:")

for product in products:
    print(f"- {product}")

Example interaction:

How many products? 3
Product 1: Keyboard
Product 2: Mouse
Product 3: Notebook

Output:

Your products:
- Keyboard
- Mouse
- Notebook

This is a real list-building program.

The user gives values.

Python stores them in a list.

Then Python loops through the list and prints them.

Very useful.

Very beginner-friendly.

Very close to real applications.

Lists with Conditions

You can use conditions while looping through a list.

Example:

prices = [10.99, 120.00, 5.50, 250.00]

for price in prices:
    if price >= 100:
        print(f"Expensive item: {price:.2f}")

Output:

Expensive item: 120.00
Expensive item: 250.00

This means:

Go through all prices.
Print only prices that are 100 or more.

This is filtering.

Filtering means:

Show only the items that match a condition.

Very common.

Very useful.

Very database-like.

PostgreSQL is watching proudly from the corner.

Creating a New Filtered List

You can create a new list from selected items.

Example:

prices = [10.99, 120.00, 5.50, 250.00]

expensive_prices = []

for price in prices:
    if price >= 100:
        expensive_prices.append(price)

print(expensive_prices)

Output:

[120.0, 250.0]

What happens?

Start with an empty list.
Loop through all prices.
If price is expensive, add it to expensive_prices.
Print the new list.

This is another very common pattern.

Loop.

Check.

Append.

Congratulations.

You are now doing real data processing.

Small data.

But real.

Common Mistake: Index Out of Range

This is wrong:

products = ["Keyboard", "Mouse", "Notebook"]

print(products[3])

Python gives an error:

IndexError

Why?

Because the list has 3 items.

Their indexes are:

0
1
2

There is no index 3.

Remember:

products[0]  # first item
products[1]  # second item
products[2]  # third item

The last index is:

length - 1

If a list has 3 items, the last index is 2.

Python is not being cruel.

It is just counting from zero again.

Classic Python.

Common Mistake: Forgetting Quotes

Wrong:

products = [Keyboard, Mouse, Notebook]

Python thinks Keyboard, Mouse, and Notebook are variable names.

But they are not defined.

Correct:

products = ["Keyboard", "Mouse", "Notebook"]

Strings need quotes.

Variables do not.

This rule returns again and again.

Like a bug you thought you fixed.

But friendlier.

Common Mistake: Using append() Wrong

Wrong:

products = ["Keyboard"]

products.append("Mouse", "Notebook")

This gives an error.

Why?

Because append() adds one item at a time.

Correct:

products = ["Keyboard"]

products.append("Mouse")
products.append("Notebook")

Output:

['Keyboard', 'Mouse', 'Notebook']

For now, remember:

append() adds one item.

Later, you will learn other ways to add multiple items.

Python has more tools.

Of course it does.

The toolbox never ends.

Common Mistake: Removing Missing Items

Wrong:

products = ["Keyboard", "Mouse"]

products.remove("Notebook")

This causes:

ValueError

Because "Notebook" is not in the list.

Safer:

products = ["Keyboard", "Mouse"]

if "Notebook" in products:
    products.remove("Notebook")
else:
    print("Notebook was not found.")

Always be careful when removing items.

Lists do not magically remove things that are not there.

That would be a philosophical problem.

And Python is not in the mood.

Common Mistake: Confusing Index and Value

Look at this list:

products = ["Keyboard", "Mouse", "Notebook"]

Index:

0, 1, 2

Values:

Keyboard, Mouse, Notebook

This accesses by index:

print(products[1])

Output:

Mouse

This removes by value:

products.remove("Mouse")

Important difference:

index = position
value = actual item

Do not confuse them.

Index is where the thing is.

Value is the thing.

Very simple.

Very easy to forget.

Very beginner-normal.

Mini Program: Shopping List

Create a file:

shopping_list.py

Write:

shopping_list = []

while True:
    item = input("Add item or type q to quit: ")

    if item == "q":
        break

    shopping_list.append(item)

print("Your shopping list:")

for item in shopping_list:
    print(f"- {item}")

Example:

Add item or type q to quit: Bread
Add item or type q to quit: Milk
Add item or type q to quit: Eggs
Add item or type q to quit: q

Output:

Your shopping list:
- Bread
- Milk
- Eggs

This program uses:

Many concepts together.

Very strong practice.

Very real.

Very useful if you actually remember to buy the eggs.

Mini Program: Average Score

Create a file:

average_score.py

Write:

scores = []

score_count = int(input("How many scores? "))

for number in range(1, score_count + 1):
    score = float(input(f"Score {number}: "))
    scores.append(score)

total = 0

for score in scores:
    total += score

average = total / len(scores)

print(f"Average score: {average:.2f}")

Example:

How many scores? 3
Score 1: 80
Score 2: 90
Score 3: 70

Output:

Average score: 80.00

This program uses:

This is a serious beginner program.

Not huge.

But serious.

The Python soup is getting richer again.

Still no USB flavor.

Good.

Mini Program: Product Prices

Create a file:

product_prices.py

Write:

prices = []

product_count = int(input("How many products? "))

for number in range(1, product_count + 1):
    price = float(input(f"Price for product {number}: "))
    prices.append(price)

total = 0

for price in prices:
    total += price

print(f"Total: {total:.2f}")

if total >= 100:
    print("Big order.")
else:
    print("Small order.")

Example:

How many products? 3
Price for product 1: 20
Price for product 2: 30
Price for product 3: 60

Output:

Total: 110.00
Big order.

Now we combine:

lists
loops
conditions
numbers
input
formatted output

This is how real programs are built.

Concept by concept.

Line by line.

Tiny brick.

Tiny brick.

Eventually, the house appears.

Hopefully not haunted by indentation errors.

Practice

Create a file:

practice_lists.py

Write a program that:

Example solution:

names = []

name_count = int(input("How many names? "))

for number in range(1, name_count + 1):
    name = input(f"Name {number}: ")
    names.append(name)

print("Names:")

for name in names:
    print(f"- {name}")

print(f"Total names: {len(names)}")

if "Anna" in names:
    print("Anna is in the list.")
else:
    print("Anna is not in the list.")

Try it.

Change names.

Try adding Anna.

Try not adding Anna.

The program should react differently.

Lists plus conditions.

Very useful.

Very real.

Mini Challenge

Create a file:

task_manager.py

Your program should:

Menu:

1. Add task
2. Show tasks
q. Quit

Example solution:

tasks = []

while True:
    print("----- Task Manager -----")
    print("1. Add task")
    print("2. Show tasks")
    print("q. Quit")

    choice = input("Choose an option: ").lower()

    if choice == "1":
        task = input("Task: ")
        tasks.append(task)
        print("Task added.")
    elif choice == "2":
        print("Tasks:")

        if len(tasks) == 0:
            print("No tasks yet.")
        else:
            for task in tasks:
                print(f"- {task}")
    elif choice == "q":
        print("Goodbye.")
        break
    else:
        print("Unknown option.")

This is a real mini application.

It uses:

Small project.

Big progress.

This is how command-line tools begin.

Before they become web apps.

Before they become dashboards.

Before someone asks:

Can we add login?

And the adventure becomes longer.

Extra Challenge: Remove Tasks

Improve task_manager.py.

Add one more menu option:

3. Remove task

Then allow the user to type a task name and remove it.

Example idea:

elif choice == "3":
    task = input("Task to remove: ")

    if task in tasks:
        tasks.remove(task)
        print("Task removed.")
    else:
        print("Task not found.")

This adds:

Now your task manager can add, show, and remove tasks.

Still small.

But very useful.

A tiny productivity app.

Try not to spend three hours improving it.

Or do.

That is also how programmers are made.

Beginner Checklist

When your list program does not work, check:

Did I use square brackets for the list?
Did I separate items with commas?
Did I put strings in quotes?
Did I remember indexes start at 0?
Am I trying to access an index that does not exist?
Did I use append() with one item?
Did I check if an item exists before remove()?
Did I indent the loop body correctly?
Did I use len() when I needed the number of items?
Did I confuse index and value?

Lists are simple at first.

Then very powerful.

Most beginner list errors come from indexes.

Indexes start at zero.

The first item is index 0.

The last item is often:

list_name[-1]

Remember this.

Your future debugging time will thank you.

Probably silently.

Summary

Today you learned:

This is a huge step.

Now your programs can store many values.

They can process collections of data.

They can build shopping lists.

They can calculate totals.

They can manage tasks.

They can work with many inputs.

This is much closer to real programming.

One value is nice.

Many values are reality.

Next Lesson

In the next lesson, we will learn dictionaries.

Dictionaries let you store data using keys and values.

Instead of only storing:

["Anna", 25, "Rome"]

you will be able to write:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

This is very important.

Lists are great for many values.

Dictionaries are great for structured data.

And structured data is everywhere.

Users.

Products.

Orders.

Profiles.

APIs.

Very useful.

Very Python.