Table of Contents
Understanding Lists in Python
Lists are one of the most commonly used data collections in Python. They are ordered, changeable (mutable), and can hold a mix of different data types.
This chapter focuses specifically on how to create, use, and modify lists.
Creating Lists
A list is written with square brackets [], with items separated by commas.
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]
empty_list = []
You can also create a list using the list() function:
text = "hello"
characters = list(text) # ['h', 'e', 'l', 'l', 'o']Accessing List Items (Indexing)
List items are ordered. Each item has a position (index), starting from 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherryNegative indexes count from the end:
-1is the last item-2is the second-to-last item
print(fruits[-1]) # cherry
print(fruits[-2]) # bananaChanging Items in a List
Lists are mutable, so you can change items after the list is created.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']You can also change several items at once using slicing (explained next).
Slicing Lists
Slicing lets you get a part (sub-list) of a list.
General form:
$$
\text{list}[start:end]
$$
startindex is includedendindex is excluded
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30] (from start to index 2)
print(numbers[2:]) # [30, 40, 50] (from index 2 to end)You can also use slices to replace multiple items:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = [10, 11, 12]
print(numbers) # [0, 10, 11, 12, 4, 5]Adding Items to a List
`append()` – add to the end
append() adds a single item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']`insert()` – add at a specific position
insert(index, item) inserts an item at a specific position, moving later items to the right.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits) # ['apple', 'banana', 'cherry']`extend()` – add multiple items
extend() adds all items from another list (or any iterable) to the end.
fruits = ["apple", "banana"]
more_fruits = ["cherry", "date"]
fruits.extend(more_fruits)
print(fruits) # ['apple', 'banana', 'cherry', 'date']Removing Items from a List
`remove()` – remove by value
Removes the first matching value.
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana']
If the value is not in the list, remove() causes an error.
`pop()` – remove by index
Removes and returns the item at a given index. If no index is given, removes the last item.
fruits = ["apple", "banana", "cherry"]
last = fruits.pop()
print(last) # cherry
print(fruits) # ['apple', 'banana']
first = fruits.pop(0)
print(first) # apple
print(fruits) # ['banana']`del` – delete by index or slice
del is a Python keyword used to delete items.
numbers = [10, 20, 30, 40, 50]
del numbers[1] # delete item at index 1
print(numbers) # [10, 30, 40, 50]
del numbers[1:3] # delete a slice
print(numbers) # [10, 50]`clear()` – remove all items
Empties the list but keeps the list object.
numbers = [1, 2, 3]
numbers.clear()
print(numbers) # []Checking if an Item Is in a List
Use the in keyword to test if a value exists in the list.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("orange" in fruits) # False
if "apple" in fruits:
print("We have apples!")Getting the Length of a List
Use len() to find out how many items are in a list.
fruits = ["apple", "banana", "cherry"]
count = len(fruits)
print(count) # 3Looping Over a List
You will learn loops in detail elsewhere, but here is how they commonly work with lists.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)This prints each item in the list, one per line.
Sorting and Reversing Lists
`sort()` – sort the list in place
sort() changes the existing list into a sorted version.
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5]
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits) # ['apple', 'banana', 'cherry']You can sort in reverse order:
numbers = [3, 1, 4, 1, 5]
numbers.sort(reverse=True)
print(numbers) # [5, 4, 3, 1, 1]`sorted()` – return a new sorted list
sorted() does not change the original list; it returns a new one.
numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
print(numbers) # [3, 1, 4, 1, 5]
print(sorted_numbers) # [1, 1, 3, 4, 5]`reverse()` – reverse the list order
Reverses the list in place, without sorting.
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers) # [4, 3, 2, 1]Copying Lists
Assigning one list to another variable does not make a copy; it makes a second name for the same list.
a = [1, 2, 3]
b = a # NOT a copy!
b.append(4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]To make a real (shallow) copy, use one of these:
a = [1, 2, 3]
b = a.copy()
# or
b = list(a)
# or
b = a[:] # slice from start to end
b.append(4)
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]Joining and Repeating Lists
Joining lists with `+`
a = [1, 2]
b = [3, 4]
c = a + b
print(c) # [1, 2, 3, 4]Repeating lists with `*`
zeros = [0] * 5
print(zeros) # [0, 0, 0, 0, 0]Useful List Methods (Overview)
Some common list methods you have seen or will see:
append(x)– addxto the endinsert(i, x)– insertxat positioniextend(iterable)– add all items from another iterableremove(x)– remove the first occurrence ofxpop([i])– remove and return item at indexi(or last item)clear()– remove all itemsindex(x)– get the index of the first occurrence ofxcount(x)– count how many timesxappearssort()– sort the listreverse()– reverse the listcopy()– return a shallow copy
Example of index() and count():
numbers = [1, 2, 3, 2, 2, 4]
print(numbers.index(3)) # 2 (position of first 3)
print(numbers.count(2)) # 3 (three 2's)Simple Practice Ideas with Lists
Some small ideas to practice working with lists:
- Store a list of your favorite movies and:
- Add a new movie
- Remove one you no longer like
- Print how many movies are in the list
- Ask the user for 3 numbers, store them in a list, and:
- Print the list
- Print the smallest and largest number (using
min()andmax()) - Create a list of names and:
- Sort them
- Print them one per line using a
forloop
Lists are a core part of Python programming, and you will use them again in loops, functions, file handling, and many later topics.