Python Introduction to Lists
Table of Contents
In the last lesson, we learned about Python Regular Expressions. Now let’s use lists to keep many values together in one place.
Let’s Talk About Collections
So far, we have worked with single values.
One number. One string. One boolean.
But what if we have many values? Like a list of names. Or a list of scores. Or a list of items in a shopping cart.
We could create separate variables for each one.
name1 = "Alex"name2 = "Sam"name3 = "John"But that gets messy fast. What if we have 100 names? We would need 100 variables. That is not practical.
That is where lists come in.
What Is a List in Python?
A list is a collection of items. We can put many values in one list. And we can access them by position.
Think of it like a shopping list. We write down multiple items on one piece of paper. We can read them, add to them, remove them, and change them.
In Python, a list is exactly like that. It is an ordered collection of items.
How to Create a List in Python
We create a list by putting items inside square brackets [ ], separated by commas.
names = ["Alex", "Sam", "John"]numbers = [1, 2, 3, 4, 5]mixed = [1, "hello", True, 3.14]That’s it. Just square brackets and commas.
We can have a list of strings. A list of numbers. A list of booleans. Even a list of mixed types. Python does not care.
Accessing Items in a Python List
We access items using their index. Just like strings.
names = ["Alex", "Sam", "John"]print(names[0])Output
AlexLet’s remember, indexing starts at 0. So names[0] is the first item. names[1] is the second. And so on.
print(names[0]) # Alexprint(names[1]) # Samprint(names[2]) # JohnNegative indexing works too.
print(names[-1]) # John (last item)print(names[-2]) # Samprint(names[-3]) # AlexChanging Items in a Python List
Unlike strings, lists are mutable. That means we can change them.
names = ["Alex", "Sam", "John"]names[1] = "Emma"print(names)Output
['Alex', 'Emma', 'John']We changed the item at index 1 from “Sam” to “Emma”. And the list was updated.
That is a big difference between strings and lists. Strings cannot be changed. Lists can.
Adding Items to a Python List
We can add items to a list using append(). It adds to the end.
names = ["Alex", "Sam"]names.append("John")print(names)Output
['Alex', 'Sam', 'John']We can also add to a specific position using insert().
names = ["Alex", "Sam"]names.insert(1, "Emma")print(names)Output
['Alex', 'Emma', 'Sam']It inserted “Emma” at index 1. And the rest shifted to the right.
Removing Items from a Python List
We can remove items using remove() or pop().
remove() removes the first occurrence of a value.
names = ["Alex", "Sam", "John"]names.remove("Sam")print(names)Output
['Alex', 'John']pop() removes an item by index. If we do not give an index, it removes the last item.
names = ["Alex", "Sam", "John"]names.pop(1)print(names)Output
['Alex', 'John']names.pop()print(names)Output
['Alex']The Length of a Python List
We use len() to get the number of items.
names = ["Alex", "Sam", "John"]print(len(names))Output
3Checking If an Item Is in a List
We use in.
names = ["Alex", "Sam", "John"]print("Sam" in names)Output
Trueprint("Emma" in names)Output
FalseLooping Through a Python List
We can use a for loop to go through each item.
names = ["Alex", "Sam", "John"]for name in names: print(f"Hello, {name}")Output
Hello, AlexHello, SamHello, JohnThat is one of the most common things we will do with lists.
Slicing a Python List
We can slice a list just like a string.
numbers = [10, 20, 30, 40, 50]print(numbers[1:4])Output
[20, 30, 40]Same rules. Start is inclusive. End is exclusive. Step is optional.
We can reverse a list with slicing.
print(numbers[::-1])Output
[50, 40, 30, 20, 10]Python Lists: A Real-Life Example
Let’s build a simple to-do list.
todos = []
while True: task = input("Enter a task (or 'quit' to stop): ") if task.lower() == "quit": break todos.append(task)
print("\nYour to-do list:")for i, task in enumerate(todos, 1): print(f"{i}. {task}")Output
Enter a task (or 'quit' to stop): Buy groceriesEnter a task (or 'quit' to stop): Call momEnter a task (or 'quit' to stop): Finish projectEnter a task (or 'quit' to stop): quit
Your to-do list:1. Buy groceries2. Call mom3. Finish projectThat uses a list to store tasks. And a loop to add them. And another loop to display them.
Notice enumerate(todos, 1). It gives us both the index and the item. And the 1 means start counting from 1 instead of 0. That is handy for numbered lists.
Python Lists Can Hold Anything
A list can hold numbers, strings, booleans, other lists, even functions. Anything.
mixed = [1, "hello", True, 3.14, [1, 2, 3]]That is valid. But usually, we want our lists to be of one type. It makes them easier to work with.
Common Mistakes with Python Lists
Mistake 1: Using Parentheses Instead of Square Brackets
names = ("Alex", "Sam") # This is a tuple, not a listTuples are similar but immutable. We will cover them later. For now, let’s use square brackets for lists.
Mistake 2: Going Out of Range
names = ["Alex", "Sam"]print(names[5]) # Error!Output
IndexError: list index out of rangeSo what do we do? We check the length first, or use a valid index.
Mistake 3: Thinking append() Returns a New List
names = ["Alex"]names = names.append("Sam") # This sets names to None!print(names)Output
NoneBecause append() changes the list in place and returns None. Let’s not assign the result.
So what do we do? We just call it without assigning.
names.append("Sam")print(names)Mistake 4: Removing an Item That Does Not Exist
names = ["Alex"]names.remove("Sam") # Error!Output
ValueError: list.remove(x): x not in listSo what do we do? We check if the item is in the list first.
if "Sam" in names: names.remove("Sam")Next, we will learn about Python List Operations and read, change, and combine list values.