Skip to main content
Editor

Python Lists: Create, Access, Modify, and Loop Through Lists

Beginner30 min9 exercises175 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/9 exercises

Think about your favorite music playlist. It has a bunch of songs stored in a specific order. You can add new songs, remove old ones, rearrange them, or skip to song number five.

A Python list works exactly like that. It's an ordered collection of items that you can change whenever you want. Grocery lists, student names, high scores, pixel colors - lists are one of the most useful tools in all of Python.

In this tutorial, you'll learn how to create lists, access items by position, add and remove items, loop through them, slice them, and avoid the most common mistakes beginners make.

How to Create a List in Python

You create a list by putting items inside square brackets [], separated by commas. Each item can be any type - strings, numbers, booleans, or even other lists.

Creating lists with square brackets
# A list of strings
fruits = ["apple", "banana", "cherry"]
print(fruits)
# A list of numbers
scores = [95, 87, 72, 100, 68]
print(scores)
# A list with mixed types
mixed = ["Alice", 15, True, 3.14]
print(mixed)
Output
['apple', 'banana', 'cherry']
[95, 87, 72, 100, 68]
['Alice', 15, True, 3.14]

Each item in the list has a position called an index. The first item is at index 0, the second is at index 1, and so on. This "start at zero" rule is the same in almost every programming language.

You can also create an empty list and add items to it later. This is common when you don't know ahead of time what your list will contain.

Empty lists and the list() constructor
# Empty list - two ways to create one
empty1 = []
empty2 = list()
print(empty1) # []
print(empty2) # []
# The list() constructor can also convert other things into lists
letters = list("hello")
print(letters) # ['h', 'e', 'l', 'l', 'o']
Output
[]
[]
['h', 'e', 'l', 'l', 'o']

How to Access List Items by Index in Python

To grab a single item from a list, put its index number inside square brackets after the list name. Remember, indexing starts at 0, not 1.

Accessing items with positive indexes
colors = ["red", "green", "blue", "yellow", "purple"]
# Positive indexing (from the front)
print(colors[0]) # red (first item)
print(colors[1]) # green (second item)
print(colors[4]) # purple (fifth item)
Output
red
green
purple

Python also supports negative indexing, which counts from the end of the list. -1 is the last item, -2 is the second-to-last, and so on.

Accessing items with negative indexes
colors = ["red", "green", "blue", "yellow", "purple"]
# Negative indexing (from the end)
print(colors[-1]) # purple (last item)
print(colors[-2]) # yellow (second-to-last)
print(colors[-5]) # red (first item, the long way around)
Output
purple
yellow
red

Negative indexing is especially handy when you want the last item but don't know how long the list is. my_list[-1] always gives you the last one.

Checking list length to avoid IndexError
colors = ["red", "green", "blue"]
print(len(colors)) # 3 items
# This works fine:
print(colors[2]) # blue (index 2 = third item)
# This crashes:
# print(colors[3]) # IndexError! Only indexes 0, 1, 2 exist
Output
3
blue

How to Modify Lists in Python

Lists are mutable, which means you can change them after creating them. You can swap out individual items, add new ones, or combine lists together.

Changing an Item by Index

To replace a specific item, assign a new value to its index. This overwrites the old value completely.

Replacing an item by index
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']
# Change the second item
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']
Output
['apple', 'banana', 'cherry']
['apple', 'mango', 'cherry']

Adding Items with append(), insert(), and extend()

Python gives you three ways to add items to a list. Each one works a little differently.

Three ways to add items
shopping = ["milk", "eggs"]
# append() adds one item to the END
shopping.append("bread")
print(shopping) # ['milk', 'eggs', 'bread']
# insert() adds one item at a SPECIFIC position
shopping.insert(1, "butter") # Insert at index 1
print(shopping) # ['milk', 'butter', 'eggs', 'bread']
# extend() adds MULTIPLE items from another list
shopping.extend(["cheese", "juice"])
print(shopping) # ['milk', 'butter', 'eggs', 'bread', 'cheese', 'juice']
Output
['milk', 'eggs', 'bread']
['milk', 'butter', 'eggs', 'bread']
['milk', 'butter', 'eggs', 'bread', 'cheese', 'juice']
append() adds as one item
a = [1, 2, 3]
a.append([4, 5])
print(a)  # [1, 2, 3, [4, 5]]
extend() adds each element
a = [1, 2, 3]
a.extend([4, 5])
print(a)  # [1, 2, 3, 4, 5]

How to Remove Items from a Python List

Just like there are several ways to add items, Python gives you several ways to remove them. The right choice depends on whether you know the value or the position.

remove() and pop()
pets = ["cat", "dog", "fish", "hamster", "dog"]
# remove() deletes the FIRST matching value
pets.remove("dog")
print(pets) # ['cat', 'fish', 'hamster', 'dog']
# pop() removes by INDEX and returns the removed item
removed = pets.pop(1) # Remove index 1
print(removed) # fish
print(pets) # ['cat', 'hamster', 'dog']
# pop() with no argument removes the LAST item
last = pets.pop()
print(last) # dog
print(pets) # ['cat', 'hamster']
Output
['cat', 'fish', 'hamster', 'dog']
fish
['cat', 'hamster', 'dog']
dog
['cat', 'hamster']

remove() searches for a value and deletes the first one it finds. If the value doesn't exist, Python raises a ValueError.

pop() removes by position and gives back the removed item. This is useful when you need to use that item after removing it - like dealing cards from a deck.

del and clear()
numbers = [10, 20, 30, 40, 50]
# del removes by index (doesn't return the value)
del numbers[0]
print(numbers) # [20, 30, 40, 50]
# clear() removes ALL items
numbers.clear()
print(numbers) # []
Output
[20, 30, 40, 50]
[]

How to Loop Through a Python List

One of the most powerful things you can do with a list is loop through it - run some code once for every item. This is how you process a hundred items without writing a hundred lines.

Basic for loop over a list
fruits = ["apple", "banana", "cherry"]
# The basic for loop
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry

Read this as: "for each fruit in the fruits list, print that fruit." Python picks up the first item, runs the indented code, picks up the next item, runs it again, and so on until the list is done.

Sometimes you need the index number along with the item. The enumerate() function gives you both.

Using enumerate() to get index and value
fruits = ["apple", "banana", "cherry"]
# enumerate() gives you the index AND the item
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output
0: apple
1: banana
2: cherry

You can also loop using a range of index numbers. This is useful when you need to compare or modify items by their position.

Looping with range and index
scores = [85, 92, 78, 95, 88]
# Loop using range(len(...))
for i in range(len(scores)):
print(f"Student {i + 1}: {scores[i]}")
Output
Student 1: 85
Student 2: 92
Student 3: 78
Student 4: 95
Student 5: 88

How to Check If an Item Is in a Python List

The in keyword checks whether a value exists in a list. It returns True or False.

Using in and not in
colors = ["red", "green", "blue"]
print("red" in colors) # True
print("yellow" in colors) # False
# You can use it in if statements
if "green" in colors:
print("Green is in the list!")
# not in checks for absence
if "purple" not in colors:
print("Purple is NOT in the list.")
Output
True
False
Green is in the list!
Purple is NOT in the list.

This is much cleaner than writing a loop to search for a value manually. Use in anytime you need to check whether something exists in a list.

Python List Slicing

Slicing lets you grab a portion of a list instead of a single item. The syntax is list[start:end], where start is included and end is not included.

Basic list slicing
letters = ["a", "b", "c", "d", "e", "f"]
# Basic slicing: [start:end]
print(letters[1:4]) # ['b', 'c', 'd'] - indexes 1, 2, 3
# Omit start - defaults to beginning
print(letters[:3]) # ['a', 'b', 'c']
# Omit end - defaults to the end
print(letters[3:]) # ['d', 'e', 'f']
# Both omitted - copies the entire list
print(letters[:]) # ['a', 'b', 'c', 'd', 'e', 'f']
Output
['b', 'c', 'd']
['a', 'b', 'c']
['d', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']

The "end is not included" rule feels weird at first, but it has a nice benefit: letters[:3] gives you exactly 3 items, and letters[3:] gives you the rest. No off-by-one confusion.

You can add a third number called the step. This tells Python how far to move between each pick: a step of 2 takes every other item.

Slicing with a step
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [start:end:step]
print(numbers[0:10:2]) # [0, 2, 4, 6, 8] - every other item
print(numbers[::3]) # [0, 3, 6, 9] - every third item
# Negative step reverses the list
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Output
[0, 2, 4, 6, 8]
[0, 3, 6, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Useful Python List Methods

Python lists come with many built-in methods. Here are the ones you'll use most often.

sort(), reverse(), and count()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort() arranges items in order (changes the original list)
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# reverse() flips the list order
numbers.reverse()
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# count() tells you how many times a value appears
print(numbers.count(1)) # 2
Output
[1, 1, 2, 3, 4, 5, 6, 9]
[9, 6, 5, 4, 3, 2, 1, 1]
2
len(), min(), max(), and sum()
scores = [85, 92, 78, 95, 88]
# len() - number of items
print(len(scores)) # 5
# min() - smallest value
print(min(scores)) # 78
# max() - largest value
print(max(scores)) # 95
# sum() - total of all items
print(sum(scores)) # 438
# Calculate the average
average = sum(scores) / len(scores)
print(f"Average: {average}") # Average: 87.6
Output
5
78
95
438
Average: 87.6

Common Python List Mistakes

Lists have a few tricky behaviors that trip up almost every beginner. Understanding these now will save you hours of debugging later.

Aliasing: both names point to the same list
# The aliasing problem
original = [1, 2, 3]
alias = original # NOT a copy!
alias.append(4)
print(original) # [1, 2, 3, 4] - original changed too!
print(alias) # [1, 2, 3, 4]
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
Making a proper copy with [:]
# The fix: make a real copy
original = [1, 2, 3]
real_copy = original[:] # Slice copy
real_copy.append(4)
print(original) # [1, 2, 3] - original is untouched
print(real_copy) # [1, 2, 3, 4]
Output
[1, 2, 3]
[1, 2, 3, 4]
Alias (same object)
a = [1, 2, 3]
b = a         # b IS a
b.append(4)
print(a)      # [1, 2, 3, 4]
Copy (separate object)
a = [1, 2, 3]
b = a[:]      # b is a COPY of a
b.append(4)
print(a)      # [1, 2, 3]

Practice Exercises

Time to practice! These exercises build on each other, going from basic to more challenging. Try each one before looking at hints.

Exercise 1: Create a List and Print Its Length
Write Code

Create a list called animals containing these three strings: "cat", "dog", "rabbit".

Then print the length of the list in this exact format:

3
# Create your list
# Print the length
Exercise 2: Access the Last Item with Negative Indexing
Write Code

A list of cities is given. Use negative indexing to print the last city in the list.

Expected output:

Tokyo
cities = ["Paris", "London", "New York", "Tokyo"]
# Print the last city using negative indexing
Exercise 3: Shopping List: Add and Remove Items
Write Code

You have a shopping list. Do these steps in order:

1. Add "bread" to the end of the list

2. Remove "milk" from the list

3. Print the final list

Expected output:

['eggs', 'cheese', 'butter', 'bread']
shopping = ["eggs", "milk", "cheese", "butter"]
# Step 1: Add "bread" to the end
# Step 2: Remove "milk"
# Step 3: Print the list
Exercise 4: Fix the Bug: IndexError
Fix the Bug

This code tries to print the last color in the list, but it crashes with an IndexError. Fix the bug so it prints:

purple

Hint: The list has 4 items. What are the valid indexes?

colors = ["red", "green", "blue", "purple"]
print(colors[4])
Exercise 5: Sum All Numbers Using a Loop
Write Code

Write a program that calculates the sum of all numbers in the list using a for loop. Do not use the built-in sum() function.

Expected output:

150
numbers = [10, 20, 30, 40, 50]
# Calculate the total using a for loop
# Print the total
Exercise 6: Find the Largest Number Without max()
Write Code

Find the largest number in the list using a for loop. Do not use the built-in max() function.

Expected output:

95
scores = [72, 85, 95, 60, 88]
# Find the largest score using a loop
# Print the largest score
Exercise 7: Predict the Output: List Aliasing
Predict Output

Read this code carefully and predict what it will print. Think about what happens when two variables point to the same list.

Type the exact output (each value on a new line if there are multiple prints).

a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
Exercise 8: Reverse a List Without reverse() or [::-1]
Write Code

Reverse the given list using a loop. Do not use reverse(), reversed(), or [::-1].

Expected output:

[5, 4, 3, 2, 1]
original = [1, 2, 3, 4, 5]
# Reverse the list using a loop
# Print the reversed list
Page Ranges
Stretch

A print dialog shows the pages you picked in a short form, joining runs of pages that follow each other. Write a function page_ranges(pages) that takes a list of page numbers and returns that text.

page_ranges([1, 2, 3, 5, 7, 8, 9])   # '1-3, 5, 7-9'
page_ranges([4, 10])                  # '4, 10'

The list can be in any order and can name a page more than once. A run of one page is written as the page alone. With no pages, return an empty string.

Return the answer instead of printing it: Check calls page_ranges() with its own lists, some of them hidden.

def page_ranges(pages):
pass
Solution unlocks after your first Check

Summary: What You Learned About Python Lists

Great job making it through this tutorial! Here's a recap of everything you now know:

ConceptWhat it doesExample
Create a listStore items in orderfruits = ["a", "b"]
Access by indexGet one itemfruits[0], fruits[-1]
Modify itemsChange a valuefruits[0] = "cherry"
append()Add to endfruits.append("date")
insert()Add at positionfruits.insert(1, "fig")
remove()Delete by valuefruits.remove("a")
pop()Delete by indexfruits.pop(0)
for loopProcess each itemfor f in fruits:
in / not inCheck membership"a" in fruits
SlicingGet a portionfruits[1:3]
sort() / reverse()Reorder itemsfruits.sort()
len() / sum()Count or totallen(fruits)

Lists are one of the most frequently used data structures in Python. Almost every real program uses them - from web apps to data science to game development.

What's Next?

In the next tutorial - Python List Comprehensions - you'll learn a powerful shortcut for creating and transforming lists in a single line of code.

You'll see how to replace 4 lines of loop code with one clean line, and learn when comprehensions make sense versus when a regular loop is better.

Harder problems

More problems on this topic: Lists

Related Tutorials

Was this tutorial helpful?