Lists in Python
Reviewed & published by Brayan K
Store and manage multiple values in a single variable using Python lists.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- What a list is and why it's Python's most-used data structure
- How to access items by index (including negative indexing)
- How to add, remove, and change items in a list
- How to slice lists to extract subsets
- How to loop through lists and search for items
- Useful list methods: sort, reverse, count, len
1. What Are Lists?
A list is a collection that stores multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.
Key Characteristics
- Ordered — Items have a defined order (index 0, 1, 2...)
- Mutable — You can add, remove, or change items
- Allow duplicates — Same value can appear multiple times
- Mixed types — Can hold strings, numbers, booleans, etc.
2. Creating Lists
| Type | Example | Description |
|---|---|---|
| Empty list | my_list = [] | Start with nothing |
| Strings | ["a", "b", "c"] | List of text values |
| Numbers | [1, 2, 3, 4, 5] | List of integers |
| Mixed | [1, "hello", True] | Different types together |
| Nested | [[1, 2], [3, 4]] | Lists inside lists |
# Different ways to create lists
# Empty list
my_list = []
print("Empty:", my_list)
# List with strings
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)
# List with numbers
numbers = [10, 20, 30, 40, 50]
print("Numbers:", numbers)
# Mixed types
mixed = [1, "hello", True, 3.14]
print("Mixed:", mixed)
# How many items?
print(f"Fruits has {len(fruits)} items")
# ✅ Expected output:
# Empty: []
# Fruits: ['apple', 'banana', 'cherry']
# Numbers: [10, 20, 30, 40, 50]
# Mixed: [1, 'hello', True, 3.14]
# Fruits has 3 items3. Accessing Items by Index
Each item in a list has an index (position number). Python uses zero-based indexing — the first item is at index 0.
| Code | Result | Explanation |
|---|---|---|
| fruits[0] | "apple" | First item |
| fruits[2] | "cherry" | Third item |
| fruits[-1] | "date" | Last item (negative index) |
| fruits[-2] | "cherry" | Second to last |
fruits = ["apple", "banana", "cherry", "date"]
# Positive indexing (from start)
print("First item:", fruits[0])
print("Second item:", fruits[1])
print("Third item:", fruits[2])
# Negative indexing (from end)
print("Last item:", fruits[-1])
print("Second to last:", fruits[-2])
# Get length of list
print(f"Total items: {len(fruits)}")
# ✅ Expected output:
# First item: apple
# Second item: banana
# Third item: cherry
# Last item: date
# Second to last: cherry
# Total items: 44. Changing List Items
Lists are mutable — you can change items after creation by assigning a new value to a specific index.
colors = ["red", "green", "blue"]
print("Original:", colors)
# Change single item
colors[0] = "yellow"
print("After change:", colors)
# Change last item
colors[-1] = "purple"
print("After another change:", colors)
# ✅ Expected output:
# Original: ['red', 'green', 'blue']
# After change: ['yellow', 'green', 'blue']
# After another change: ['yellow', 'green', 'purple']5. Adding Items to Lists
| Method | What It Does | Example |
|---|---|---|
| .append(item) | Add item to the end | fruits.append("mango") |
| .insert(i, item) | Add item at position i | fruits.insert(1, "pear") |
| .extend(list) | Add all items from another list | fruits.extend(["kiwi", "lime"]) |
fruits = ["apple", "banana"]
print("Start:", fruits)
# append - add to end
fruits.append("cherry")
print("After append:", fruits)
# insert - add at specific position
fruits.insert(1, "blueberry")
print("After insert at 1:", fruits)
# extend - add multiple items
fruits.extend(["date", "elderberry"])
print("After extend:", fruits)
# ✅ Expected output:
# Start: ['apple', 'banana']
# After append: ['apple', 'banana', 'cherry']
# After insert at 1: ['apple', 'blueberry', 'banana', 'cherry']
# After extend: ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']6. Removing Items from Lists
| Method | What It Does | Example |
|---|---|---|
| .remove(item) | Remove first match by value | fruits.remove("banana") |
| .pop() | Remove and return last item | last = fruits.pop() |
| .pop(i) | Remove and return item at index i | first = fruits.pop(0) |
| .clear() | Remove all items | fruits.clear() |
| del list[i] | Delete item at index i | del fruits[0] |
fruits = ["apple", "banana", "cherry", "banana", "date"]
print("Start:", fruits)
# remove - by value (first occurrence only)
fruits.remove("banana")
print("After remove banana:", fruits)
# pop - remove and return last item
last = fruits.pop()
print(f"Popped: {last}, Remaining:", fruits)
# pop(0) - remove first item
first = fruits.pop(0)
print(f"Popped first: {first}, Remaining:", fruits)
# ✅ Expected output:
# Start: ['apple', 'banana', 'cherry', 'banana', 'date']
# After remove banana: ['apple', 'cherry', 'banana', 'date']
# Popped: date, Remaining: ['apple', 'cherry', 'banana']
# Popped first: apple, Remaining: ['cherry', 'banana']7. List Slicing — Get a Range of Items
Slicing lets you get a portion of a list using the syntax list[start:end].
| Code | Result | Meaning |
|---|---|---|
| nums[1:4] | [1, 2, 3] | Index 1 to 3 (4 excluded) |
| nums[:3] | [0, 1, 2] | First 3 items |
| nums[3:] | [3, 4, 5] | From index 3 to end |
| nums[-2:] | [4, 5] | Last 2 items |
| nums[::2] | [0, 2, 4] | Every 2nd item |
| nums[::-1] | [5, 4, 3, 2, 1, 0] | Reversed list |
nums = [0, 1, 2, 3, 4, 5]
print("Original:", nums)
# Get a range
print("nums[1:4]:", nums[1:4]) # [1, 2, 3]
# From start / to end
print("nums[:3]:", nums[:3]) # [0, 1, 2]
print("nums[3:]:", nums[3:]) # [3, 4, 5]
# Negative slicing
print("Last 2:", nums[-2:]) # [4, 5]
# With step
print("Every 2nd:", nums[::2]) # [0, 2, 4]
print("Reversed:", nums[::-1]) # [5, 4, 3, 2, 1, 0]
# ✅ Expected output:
# Original: [0, 1, 2, 3, 4, 5]
# nums[1:4]: [1, 2, 3]
# nums[:3]: [0, 1, 2]
# nums[3:]: [3, 4, 5]
# Last 2: [4, 5]
# Every 2nd: [0, 2, 4]
# Reversed: [5, 4, 3, 2, 1, 0]8. Looping Through Lists
Use a for loop to go through each item:
| Method | Use When | Example |
|---|---|---|
| for item in list: | You just need the items | for fruit in fruits: |
| for i, item in enumerate(list): | You need index + item | for i, fruit in enumerate(fruits): |
fruits = ["apple", "banana", "cherry"]
# Simple loop - just items
print("Simple loop:")
for fruit in fruits:
print(fruit)
# With index using enumerate
print("\nWith index:")
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Start counting from 1 instead of 0
print("\nNumbered list:")
for num, fruit in enumerate(fruits, start=1):
print(f"{num}. {fruit}")
# ✅ Expected output:
# Simple loop:
# apple
# banana
# cherry
#
# With index:
# 0: apple
# 1: banana
# 2: cherry
#
# Numbered list:
# 1. apple
# 2. banana
# 3. cherry🟢 Worked Example: one shopping list, every skill so far
Read this top to bottom before you run it, and try to predict each printed line. The list changes as the program goes, so every print shows you the effect of the line just above it. That is the fastest way to build a mental picture of what a list actually is.
# 🟢 WORKED EXAMPLE — one shopping list, from creation to report
shopping = ["milk", "bread", "eggs"] # square brackets, items separated by commas
print("Start :", shopping)
print("How many :", len(shopping)) # len() counts items
print("First item :", shopping[0]) # positions start at 0, not 1
print("Last item :", shopping[-1]) # -1 means "last", however long the list is
# --- adding ---
shopping.append("cheese") # append() always adds to the END
print("After append :", shopping)
shopping.insert(1, "tea") # insert(position, item) — everything shuffles right
print("After insert :", shopping)
# --- changing ---
shopping[0] = "oat milk" # lists are mutable: you can overwrite a position
print("After change :", shopping)
# --- removing ---
shopping.remove("eggs") # remove() takes the VALUE, not the position
print("After remove :", shopping)
grabbed = shopping.pop() # pop() removes the last item AND gives it to you
print("Popped :", grabbed)
print("List now :", shopping)
# --- slicing: [start:stop], stop is NOT included ---
print("First two :", shopping[0:2])
print("Everything but the first:", shopping[1:])
# --- looping with a number beside each item ---
print("Numbered list:")
for number, item in enumerate(shopping, start=1): # start=1 so humans count from 1
print(f" {number}. {item}")
# --- asking questions ---
print("Is tea on the list?", "tea" in shopping)
print("Sorted copy :", sorted(shopping)) # sorted() returns a NEW list...
print("Original still:", shopping) # ...and leaves the original alone
# ✅ Expected output:
# Start : ['milk', 'bread', 'eggs']
# How many : 3
# First item : milk
# Last item : eggs
# After append : ['milk', 'bread', 'eggs', 'cheese']
# After insert : ['milk', 'tea', 'bread', 'eggs', 'cheese']
# After change : ['oat milk', 'tea', 'bread', 'eggs', 'cheese']
# After remove : ['oat milk', 'tea', 'bread', 'cheese']
# Popped : cheese
# List now : ['oat milk', 'tea', 'bread']
# First two : ['oat milk', 'tea']
# Everything but the first: ['tea', 'bread']
# Numbered list:
# 1. oat milk
# 2. tea
# 3. bread
# Is tea on the list? True
# Sorted copy : ['bread', 'oat milk', 'tea']
# Original still: ['oat milk', 'tea', 'bread']🎯 Your Turn: the test scores list
Your turn. Three blanks, everything else written. Fill them in, run it, and check against the expected output at the bottom of the file.
# 🎯 YOUR TURN — fill in the blanks marked with ___
scores = [72, 91, 58, 84]
# 1) A late paper came in at 66. Add it to the END of the list.
scores.___(66) # 👉 which list method adds to the end?
print("All scores :", scores)
# 2) Print the highest score. There is a built-in that does this in one word.
print("Highest :", ___(scores)) # 👉 max, min, len or sum?
# 3) Add each score onto the running total.
total = 0
for score in scores:
total ___ score # 👉 the shorthand for: total = total + score
print("Total :", total)
# Already written for you:
print("Average :", total / len(scores))
print("Top three :", sorted(scores, reverse=True)[0:3])
# ✅ Expected output:
# All scores : [72, 91, 58, 84, 66]
# Highest : 91
# Total : 371
# Average : 74.2
# Top three : [91, 84, 72]If your total prints as 305 you filled in blank 1 wrongly — 66 never made it onto the list, so only four scores were added up.
9. Useful List Methods
| Method/Function | What It Does | Returns |
|---|---|---|
| len(list) | Number of items | Integer |
| .sort() | Sort ascending (modifies list) | None |
| .sort(reverse=True) | Sort descending | None |
| .reverse() | Reverse the order | None |
| .count(x) | Count occurrences of x | Integer |
| .index(x) | Find position of x | Integer |
| .copy() | Create a copy | New list |
| sum(list) | Sum of numbers | Number |
| min(list) / max(list) | Smallest / largest value | Item |
numbers = [5, 2, 8, 1, 9, 2, 5]
print("Original:", numbers)
# Sorting
numbers.sort()
print("Sorted:", numbers)
numbers.sort(reverse=True)
print("Descending:", numbers)
# Counting
print(f"Count of 5: {numbers.count(5)}")
# With number lists
nums = [10, 20, 30, 40]
print(f"Sum: {sum(nums)}")
print(f"Min: {min(nums)}, Max: {max(nums)}")
print(f"Average: {sum(nums) / len(nums)}")
# ✅ Expected output:
# Original: [5, 2, 8, 1, 9, 2, 5]
# Sorted: [1, 2, 2, 5, 5, 8, 9]
# Descending: [9, 8, 5, 5, 2, 2, 1]
# Count of 5: 2
# Sum: 100
# Min: 10, Max: 40
# Average: 25.010. Checking if Item Exists
Use in and not in to check membership:
fruits = ["apple", "banana", "cherry"]
# Check if item exists
if "banana" in fruits:
print("Yes, banana is in the list!")
if "grape" not in fruits:
print("No, grape is NOT in the list")
# Practical use: safe removal
item_to_remove = "orange"
if item_to_remove in fruits:
fruits.remove(item_to_remove)
else:
print(f"{item_to_remove} not found in list")
# ✅ Expected output:
# Yes, banana is in the list!
# No, grape is NOT in the list
# orange not found in list11. List Comprehension (Advanced)
List comprehension is a concise way to create lists in one line. It is more advanced but very powerful once you learn it.
squares = []
for x in range(5):
squares.append(x ** 2)
# [0, 1, 4, 9, 16]squares = [x ** 2 for x in range(5)]
# [0, 1, 4, 9, 16]# Basic list comprehension
squares = [x ** 2 for x in range(6)]
print("Squares:", squares)
# With condition - only even numbers
evens = [x for x in range(10) if x % 2 == 0]
print("Evens:", evens)
# Transform items
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print("Uppercase:", upper_words)
# Get lengths
lengths = [len(word) for word in words]
print("Lengths:", lengths)
# ✅ Expected output:
# Squares: [0, 1, 4, 9, 16, 25]
# Evens: [0, 2, 4, 6, 8]
# Uppercase: ['HELLO', 'WORLD', 'PYTHON']
# Lengths: [5, 5, 6]12. Common Mistakes to Avoid
| Mistake | Problem | Solution |
|---|---|---|
| Index out of range | list[10] | Check len(list) first |
| Forgetting 0-indexing | Expecting first item at 1 | First item is at index 0 |
| Removing nonexistent item | .remove("x") | Check if x in list: first |
| Aliasing instead of copying | list2 = list1 | Use list2 = list1.copy() |
| Using parentheses | (1, 2, 3) | Use square brackets [1, 2, 3] |
13. Practical Examples
Example 1: Shopping Cart
# Simple shopping cart
cart = []
# Add items
cart.append("Milk")
cart.append("Eggs")
cart.append("Bread")
print("Cart:", cart)
# Remove an item
cart.remove("Milk")
print("After removing Milk:", cart)
# Check if item in cart
if "Eggs" in cart:
print("Don't forget the eggs!")
# ✅ Expected output:
# Cart: ['Milk', 'Eggs', 'Bread']
# After removing Milk: ['Eggs', 'Bread']
# Don't forget the eggs!Example 2: Grade Calculator
# Calculate average grade
grades = [85, 90, 78, 92, 88]
average = sum(grades) / len(grades)
highest = max(grades)
lowest = min(grades)
print(f"Grades: {grades}")
print(f"Average: {average:.1f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
# ✅ Expected output:
# Grades: [85, 90, 78, 92, 88]
# Average: 86.6
# Highest: 92
# Lowest: 78Example 3: To-Do List
# Simple to-do list
todos = ["Buy groceries", "Clean room", "Study Python"]
print("My To-Do List:")
for i, task in enumerate(todos, start=1):
print(f"{i}. {task}")
# Mark first task as done (remove it)
completed = todos.pop(0)
print(f"\nCompleted: {completed}")
# Add new task
todos.append("Walk the dog")
print("\nUpdated To-Do List:")
for i, task in enumerate(todos, start=1):
print(f"{i}. {task}")
# ✅ Expected output:
# My To-Do List:
# 1. Buy groceries
# 2. Clean room
# 3. Study Python
#
# Completed: Buy groceries
#
# Updated To-Do List:
# 1. Clean room
# 2. Study Python
# 3. Walk the dog🏁 Mini-Challenge: the temperature report
No blanks now — just the brief and an outline in comments. You have six temperature readings. Print how many there are, the highest, the lowest, the average to one decimal place, and then a list of only the readings that beat the average.
The last part is the real exercise: work out the average first, then build a second, empty list and append to it inside a loop. (If you already know list comprehensions, write it both ways and compare.)
# 🏁 MINI-CHALLENGE — write it yourself
readings = [12, 19, 7, 15, 22, 9]
# 1. Print how many readings there are. (len)
# 2. Print the highest and the lowest. (max, min)
# 3. Work out the average: the total divided by how many.
# Print it to one decimal place with an f-string: f"{average:.1f}"
# 4. Make an empty list called above. Loop over readings and
# append each one that is bigger than the average. Print it.
# your code here
# ✅ Expected output:
# Readings taken : 6
# Highest : 22
# Lowest : 7
# Average : 14.0
# Above average : [19, 15, 22]Summary: Quick Reference
| Operation | Syntax | Example |
|---|---|---|
| Create | [item1, item2] | fruits = ["apple", "banana"] |
| Access | list[index] | fruits[0] |
| Change | list[i] = new | fruits[0] = "apricot" |
| Add | .append(item) | fruits.append("cherry") |
| Remove | .remove(item) | fruits.remove("banana") |
| Slice | list[start:end] | fruits[1:3] |
| Length | len(list) | len(fruits) |
| Loop | for item in list: | for fruit in fruits: |
| Check exists | item in list | "apple" in fruits |
Lesson complete — you've unlocked Python's most-used data structure!
Lists are everywhere in Python — shopping carts, user records, game inventories, search results. You can now create, access, modify, slice, sort, and loop through them.
Practice quiz
Which brackets are used to create a list?
- { }
- [ ]
- ( )
- < >
Answer: [ ]. Lists use square brackets, e.g. [1, 2, 3].
For fruits = ['apple', 'banana', 'cherry'], what is fruits[0]?
- 'banana'
- 'apple'
- 'cherry'
- Error
Answer: 'apple'. Python uses zero-based indexing, so index 0 is the first item, 'apple'.
What does fruits[-1] return?
- The first item
- The last item
- An IndexError
- The second item
Answer: The last item. Negative indexing counts from the end; -1 is the last item.
Which method adds an item to the END of a list?
- .insert()
- .append()
- .extend()
- .add()
Answer: .append(). .append(item) adds a single item to the end of the list.
What does nums[1:4] return for nums = [0, 1, 2, 3, 4, 5]?
- [1, 2, 3, 4]
- [1, 2, 3]
- [0, 1, 2, 3]
- [2, 3, 4]
Answer: [1, 2, 3]. Slicing is start-inclusive, end-exclusive: indices 1, 2, 3 give [1, 2, 3].
What does nums[::-1] produce?
- The list reversed
- Every 2nd item
- The last item
- An empty list
Answer: The list reversed. A step of -1 reverses the list.
Accessing an index that doesn't exist raises which error?
- KeyError
- ValueError
- IndexError
- TypeError
Answer: IndexError. Using an out-of-range index raises an IndexError.
What does .remove() do if the item is NOT in the list?
- Returns None
- Does nothing
- Raises a ValueError
- Adds the item
Answer: Raises a ValueError. .remove() raises a ValueError when the value isn't found.
What does sum([10, 20, 30, 40]) return?
- 100
- 4
- 40
- 25
Answer: 100. sum() adds all the numbers: 10+20+30+40 = 100.
What does [x for x in range(10) if x % 2 == 0] produce?
- [1, 3, 5, 7, 9]
- [0, 2, 4, 6, 8]
- [0, 1, 2, ..., 9]
- [2, 4, 6, 8, 10]
Answer: [0, 2, 4, 6, 8]. The comprehension keeps even numbers from 0 to 9: [0, 2, 4, 6, 8].
Continue this course
- Previous: Functions
- Next: Dictionaries — Work with key-value pairs to structure and look up real-world data
- Quick reference: Python cheat sheet › Lists & Comprehensions