Python Lists
Learn how to store, access, modify, organize, and process collections of values using one of Python's most important data structures: the list.
Learning Objectives
By the end of this lesson, you will be able to:
- Understand what Python lists are and why they are useful.
- Create lists and access individual elements.
- Modify, add, and remove list items.
- Use indexing, slicing, loops, and membership testing.
- Sort, reverse, and copy lists correctly.
- Work with nested lists and real-world collections.
- Avoid common list-related programming mistakes.
What Are Lists?
A list is a Python data structure used to store multiple values inside a single variable.
Instead of creating separate variables for every value, we can group related values together inside one list.
Lists are one of the most frequently used data structures in Python because they are flexible, ordered, and mutable.
fruits = ["apple", "banana", "mango"]
print(fruits)
['apple', 'banana', 'mango']
The square brackets [] tell Python that we
are creating a list.
Why Lists Matter
Imagine an online store that has 1,000 products. Creating a separate variable for every product would be inefficient.
A list allows us to keep all products together:
products = [
"Laptop",
"Keyboard",
"Mouse",
"Monitor"
]
We can then search, update, sort, remove, or process these values using Python.
Lists allow programs to work with collections of related values efficiently.
Creating Lists
Lists are created using square brackets.
fruits = ["apple", "banana", "mango"]
numbers = [10, 20, 30, 40]
names = ["Ali", "Sara", "Ahmed"]
empty_list = []
A list can contain zero, one, or many values.
Lists Are Ordered
List elements maintain their order. The first
element remains at index 0, the
second at index 1, and so on.
Accessing List Items
We access list elements using their index.
fruits = ["apple", "banana", "mango"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
apple
banana
mango
Remember: Python uses zero-based indexing.
Index Positions
For the list
["apple", "banana", "mango"]:
0→ apple1→ banana2→ mango
Positive & Negative Indexing
Python supports both positive and negative indexes.
Positive indexes start from the beginning. Negative indexes start from the end.
fruits = ["apple", "banana", "mango", "orange"]
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
apple
orange
mango
Negative indexing is particularly useful when you need the last few elements of a list.
Changing List Items
Lists are mutable. This means their elements can be changed after the list has been created.
fruits = ["apple", "banana", "mango"]
fruits[1] = "orange"
print(fruits)
['apple', 'orange', 'mango']
The element at index 1 was replaced.
Assigning to an index replaces the existing value. It does not insert a new element.
Adding Items to a List
Python provides several methods for adding elements.
append()
append() adds one item to the end of a list.
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
['apple', 'banana', 'mango']
insert()
insert() adds an item at a specific position.
fruits = ["apple", "mango"]
fruits.insert(1, "banana")
print(fruits)
['apple', 'banana', 'mango']
extend()
extend() adds multiple elements from
another iterable.
fruits = ["apple", "banana"]
more_fruits = ["mango", "orange"]
fruits.extend(more_fruits)
print(fruits)
['apple', 'banana', 'mango', 'orange']
append() vs extend()
append() adds one object as a
single element, while extend()
adds the elements from another iterable.
Removing Items
Python provides several ways to remove elements.
remove()
Removes the first matching value.
fruits = ["apple", "banana", "mango"]
fruits.remove("banana")
print(fruits)
pop()
Removes and returns an item by index. If no index is supplied, it removes the last item.
fruits = ["apple", "banana", "mango"]
removed = fruits.pop()
print(removed)
print(fruits)
mango
['apple', 'banana']
del
The del statement can remove an item by
index or even delete the entire list.
fruits = ["apple", "banana", "mango"]
del fruits[1]
print(fruits)
clear()
clear() removes all items while keeping
the list itself.
fruits = ["apple", "banana", "mango"]
fruits.clear()
print(fruits)
[]
Finding List Length
The built-in len() function tells us how
many elements a list contains.
fruits = ["apple", "banana", "mango"]
print(len(fruits))
3
This is useful when processing lists dynamically.
Checking Membership
The in and not in operators
allow us to check whether a value exists in a list.
fruits = ["apple", "banana", "mango"]
print("apple" in fruits)
print("orange" in fruits)
print("orange" not in fruits)
True
False
True
Membership testing is extremely common in real programs.
Looping Through Lists
A for loop allows us to process every
element in a list.
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
apple
banana
mango
This pattern is one of the most important ways to work with collections in Python.
Slicing Lists
List slicing allows us to extract a portion of a list.
The basic syntax is:
list[start:stop:step]
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
print(numbers[::2])
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
[10, 30, 50]
The stop index is excluded.
Copying Lists
Sometimes we need a separate copy of a list.
Using copy()
fruits = ["apple", "banana", "mango"]
new_fruits = fruits.copy()
new_fruits.append("orange")
print(fruits)
print(new_fruits)
['apple', 'banana', 'mango']
['apple', 'banana', 'mango', 'orange']
Important: Aliasing
If we write b = a, we are not creating an
independent copy. Both variables refer to the same list.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
[1, 2, 3, 4]
Both names point to the same list object.
Sorting Lists
Lists can be sorted using sort().
numbers = [50, 10, 40, 20, 30]
numbers.sort()
print(numbers)
[10, 20, 30, 40, 50]
Descending Order
numbers = [50, 10, 40, 20, 30]
numbers.sort(reverse=True)
print(numbers)
[50, 40, 30, 20, 10]
sorted()
sorted() returns a new sorted list and
leaves the original list unchanged.
numbers = [30, 10, 20]
result = sorted(numbers)
print(result)
print(numbers)
[10, 20, 30]
[30, 10, 20]
Reversing Lists
The reverse() method reverses the existing
list in place.
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
[5, 4, 3, 2, 1]
reverse() vs reversed()
reverse() modifies the list itself,
while reversed() returns an iterator
that can be used to iterate in reverse order.
Nested Lists
A list can contain other lists. Such structures are called nested lists.
matrix = [
[1, 2],
[3, 4]
]
print(matrix)
We can access nested values using multiple indexes.
matrix = [
[1, 2],
[3, 4]
]
print(matrix[0][1])
print(matrix[1][0])
2
3
Nested lists are useful for representing tables, matrices, grids, and structured data.
Lists with Mixed Data Types
Python lists can contain different data types.
student = [
"Ali",
25,
3.75,
True
]
print(student)
['Ali', 25, 3.75, True]
Although Python allows mixed-type lists, in practical applications it is often better to keep collections logically organized.
Good Programming Practice
Use lists to represent collections where the values naturally belong together. For more structured records, dictionaries or custom classes may be more appropriate.
Common List Mistakes
Mistake 1: Forgetting Zero-Based Indexing
fruits = ["apple", "banana", "mango"]
print(fruits[1])
This prints banana, not apple.
Mistake 2: Using an Invalid Index
fruits = ["apple", "banana"]
print(fruits[5])
This causes an IndexError.
Mistake 3: Confusing append() and extend()
a = [1, 2]
a.append([3, 4])
print(a)
[1, 2, [3, 4]]
The entire list [3, 4] becomes one element.
Mistake 4: Accidental Aliasing
a = [1, 2, 3]
b = a
This does not create an independent copy.
Use a.copy() when you need a separate list.
Practical Real-World Examples
Example 1: Shopping Products
cart = [
"Laptop",
"Mouse",
"Keyboard"
]
cart.append("Headphones")
for product in cart:
print(product)
Example 2: Student Marks
marks = [78, 85, 92, 69, 88]
print("Highest:", max(marks))
print("Lowest:", min(marks))
print("Total:", sum(marks))
Highest: 92
Lowest: 69
Total: 412
Example 3: Checking a User's Permission
permissions = [
"read",
"write",
"download"
]
if "write" in permissions:
print("User can modify files.")
User can modify files.
Practice Exercises
Exercise 1 — Create a List
Create a list containing five programming languages and print the list.
Exercise 2 — Access Items
Create a list of five cities. Print the first, third, and last city.
Exercise 3 — Modify a List
Create a list of three fruits. Replace the second fruit with another fruit.
Exercise 4 — Add Items
Create a list of three products. Use
append() to add another product and
insert() to add one at the beginning.
Exercise 5 — Remove Items
Create a list of five numbers and remove the third
number using pop().
Exercise 6 — Sort Numbers
Create a list of numbers in random order and sort them from smallest to largest.
Exercise 7 — List Search
Ask the user for a fruit name and check whether that fruit exists in your fruit list.
Mini Challenge — Shopping Cart Manager
Build a simple shopping cart program using lists.
Your program should:
- Create an empty shopping cart.
- Add at least five products.
- Display all products.
- Check whether a specific product exists.
- Remove one product.
- Display the final number of products.
cart = []
cart.append("Laptop")
cart.append("Mouse")
cart.append("Keyboard")
# Add more products here
print("Shopping Cart:")
for product in cart:
print("-", product)
# Check whether a product exists
# Remove a product
print("Total products:", len(cart))
Try to build the complete program yourself before looking for a solution. The goal is to practice lists, loops, membership testing, and list methods together.
Quick Knowledge Check
1. Which brackets are used to create a list?
2. What is the index of the first list element?
3. Which method adds one item to the end of a list?
4. Which method removes and returns an item?
5. What does len() return for a list?
6. What does fruits[-1] access?
7. Which method creates a shallow copy of a list?
8. What is the result of
[1, 2, 3][1:3]?
Lesson Summary
Python lists are one of the most important and flexible collection types in Python.
- Lists store multiple values in a single variable.
-
Lists use square brackets
[]. -
List indexes start at
0. - Negative indexes access elements from the end.
- Lists are mutable.
-
append()adds one item. -
insert()adds an item at a specific position. -
extend()adds multiple elements. -
remove(),pop(),del, andclear()remove elements in different ways. -
len()returns the number of elements. -
inandnot inperform membership testing. - Lists can be sliced, sorted, reversed, and copied.
- Lists can contain other lists.
-
Assigning
b = acreates an alias, not an independent copy.
Mastering lists is essential because many real Python programs work with collections of data. Lists will also become extremely important when we learn loops, functions, comprehensions, file handling, data analysis, and more advanced Python concepts.
Ready for the Next Lesson?
You've learned how Python lists store and manage collections of values.