Academic Block

Python Lists & List MethodsGet Certified

What Is a List?

A list is an ordered collection that can hold any number of items. It is the most commonly used data structure in Python: a shopping list, the scores of a class, the lines of a file, or the results of a search are all natural lists. In Python the list type is called list, and a list is written with square brackets, with the items separated by commas. A list can hold items of different types, it can contain duplicates, and it can even contain other lists.

  • Ordered: every item has a fixed position, called an index, that starts at 0.
  • Mutable: you can add, remove, and change items after the list is created.
  • Flexible: items can have different types, and the same value may appear many times.
  • Indexing and slicing: pick out one item or a piece of the list by position.
  • Methods: built-in tools such as append(), remove(), sort(), and index().
  • Nested lists: lists inside lists can store tables and grids.

Creating Lists and Accessing Items

Create a list by writing its items inside square brackets, or convert another iterable with the list() function. An empty list is written []. Items are reached with an index in square brackets: colors[0] is the first item and colors[-1] is the last. The built-in len() function returns the number of items, and the in operator checks whether a value is in the list. An index that does not exist raises an IndexError.

Try It: Creating and Reading a List

Click Test My Code. Then try colors[3] and read the error message.

What this code does: It creates a list of strings, a list of mixed types, and an empty list. It prints items by positive and negative index, prints the lengths, tests membership with in, and builds lists from a string and a range with list().
colors = ["red", "green", "blue"]
mixed = [1, "two", 3.0, True]
empty = []
print(colors[0], colors[-1])
print(len(colors), len(mixed), len(empty))
print("green" in colors, "pink" in colors)
print(list("abc"), list(range(3)))

Slicing Lists

A slice takes a part of a list with the syntax items[start:stop:step]. It works exactly like slicing a string, and the result is always a new list. The slice includes start but stops before stop. A missing value uses a default: the beginning, the end, and a step of 1. A negative step walks backwards, and items[::-1] is the quickest way to make a reversed copy. A slice that goes past the end is simply shortened and does not raise an error.

Try It: Slicing

Count the positions on paper to check each result. Then try your own slices.

What this code does: It takes slices from a list of six numbers: a middle part, the beginning and the end, every second item, the reversed list, and the last three items. It then makes a copy with [:] and compares it with the original in two ways.
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[:2], nums[4:])
print(nums[::2])
print(nums[::-1])
print(nums[-3:])
copy = nums[:]
print(copy == nums, copy is nums)

Lists Are Mutable

Unlike strings, lists can be changed in place. Assign to an index to replace one item, or assign a list to a slice to replace several items at once. The new part does not need to have the same length as the old part, so slice assignment can also grow or shrink a list. There is one important consequence of mutability: writing alias = pets does not copy the list. Both names then refer to the same list, and a change made through one name is visible through the other.

Try It: Changing a List

Click Test My Code. Watch the last output carefully: the change was made to alias, but pets shows it too.

What this code does: It replaces a single item by index, then replaces two items with three using a slice. Finally it creates a second name for the same list and shows that changing the list through the new name also changes the original name.
pets = ["cat", "dog", "fish"]
pets[1] = "hamster"
print(pets)
pets[1:3] = ["rabbit", "bird", "turtle"]
print(pets)
alias = pets
alias[0] = "lion"
print(pets)

Adding and Removing Items

Lists have a family of methods for growing and shrinking. A method that changes a list does so in place and returns None, except for pop(), which returns the item it removes.

  • append(x) adds one item to the end.
  • insert(i, x) adds an item at position i and moves the later items to the right.
  • extend(iterable) adds every item of another list or iterable to the end.
  • remove(x) deletes the first item that equals x. It raises a ValueError if there is none.
  • pop() removes and returns the last item, and pop(i) does the same for position i. It raises an IndexError on an empty list.
  • del items[i] deletes by position, and del items[a:b] deletes a slice.
  • clear() removes all items.

Try It: Growing and Shrinking a List

Click Test My Code. Follow the list on paper after each line and compare it with the output.

What this code does: It builds a list with append(), insert(), and extend(). It then removes items with remove(), pop(), pop(0), and del, and finally empties the list with clear().
items = ["a", "b"]
items.append("c")
items.insert(0, "z")
items.extend(["d", "e"])
print(items)
items.remove("b")
last = items.pop()
first = items.pop(0)
print(items, last, first)
del items[0]
print(items)
items.clear()
print(items)

Searching, Counting, and Sorting

Lists come with methods for searching and ordering. index(x) returns the position of the first match and raises a ValueError when the value is missing. count(x) returns how many times a value appears. There are two ways to sort. The sort() method sorts the list in place and returns None. The built-in sorted() function returns a new sorted list and leaves the original alone. Both accept reverse=True, and a key function that decides what to compare, such as key=len to sort by length. The built-ins min(), max(), and sum() work on lists of numbers.

Try It: index, count, sort, and reverse

Click Test My Code. Notice that sorted() leaves data unchanged, while sort() changes it.

What this code does: It finds a position and counts duplicates in a list of numbers. It shows the difference between sorted() and sort(), sorts in descending order, reverses the list, and prints the smallest, largest, and total. It then sorts a list of words by their length.
data = [5, 2, 9, 2, 7]
print(data.index(9), data.count(2))
print(sorted(data), data)
data.sort()
print(data)
data.sort(reverse=True)
print(data)
data.reverse()
print(data)
print(min(data), max(data), sum(data))
words = ["banana", "kiwi", "apple"]
words.sort(key=len)
print(words)

Combining Lists and List Comprehensions

The + operator joins two lists into a new one, and * repeats a list. Both leave the originals unchanged. A list comprehension is a compact way to build a new list from another iterable, with an optional filter: [expression for item in iterable if condition]. It does the work of a loop that appends to a list in a single line, and you will learn more about it in a later lesson. To loop over a list together with the position of each item, use enumerate().

Try It: Joining, Repeating, and Comprehensions

Click Test My Code. Change the filter in the comprehension to n % 2 == 0 to get the even numbers.

What this code does: It joins and repeats lists, and creates a list of four zeros. It builds a list of squares and a list of odd numbers with list comprehensions, and finally prints each item of a list together with its index.
a = [1, 2, 3]
b = [4, 5]
print(a + b)
print(b * 3)
print([0] * 4)
squares = [n ** 2 for n in a]
print(squares)
odd = [n for n in range(10) if n % 2 == 1]
print(odd)
for i, value in enumerate(a):
    print(i, value)

Nested Lists and Unpacking

A list can contain other lists. A list of lists is the usual way to store a table, a grid, or a matrix. Use two indexes to reach a single cell: grid[row][column]. Unpacking assigns the items of a list to several variables in one statement. A variable marked with * collects the leftover items into a list. Unpacking also gives Python its famous one-line swap, a, b = b, a.

Try It: A Grid and Unpacking

Click Test My Code. Change grid[1][2] to grid[2][0] and predict the result.

What this code does: It creates a 3 by 3 grid, reads one cell, prints the sum of every row, and collects the first column with a comprehension. It then unpacks a list into three variables and swaps two variables.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[1][2])
for row in grid:
    print(sum(row))
print([row[0] for row in grid])
first, second, *rest = [10, 20, 30, 40]
print(first, second, rest)
a, b = 1, 2
a, b = b, a
print(a, b)

Copying Lists Correctly

There are several ways to make a real copy of a list: items.copy(), items[:], and list(items). All of them make a shallow copy: the outer list is new, but the items inside are still shared. This does not matter for numbers and strings, which cannot change, but it does matter for lists inside lists. When the items are themselves mutable, use copy.deepcopy(), which also copies everything inside. A related trap is [row] * 2: it repeats the same row object twice. To build a table of independent rows, use a comprehension.

Try It: Shallow Copy, Deep Copy, and a Common Trap

Click Test My Code. Compare the outputs and find out which lists changed when original[0][0] was set to 99.

What this code does: It makes a shallow copy and a deep copy of a list of lists, changes one inner item of the original, and prints both copies. It then builds a table by repeating one row, which shares that row, and a second table with a comprehension, which does not.
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow)
print(deep)
row = [0] * 3
wrong = [row] * 2
wrong[0][0] = 1
print(wrong)
right = [[0] * 3 for _ in range(2)]
right[0][0] = 1
print(right)
Tip: Appending to the end of a list with append() is fast, but inserting or removing at the beginning, and searching with in or index(), have to look at many items and become slow for very large lists. If you only need to test membership many times, a set is the better tool, and you will meet it in a later lesson.

Using Lists with User Input

Lists are the natural way to handle input that contains many values. Read one line, split it into words, and convert the words to numbers with a list comprehension. Remember that input() returns text, so split() gives a list of strings.

Try It: A Score Analyzer

The Program Input box is already filled with 85 92 78 90 66. Click Run Code straight away, then enter your own scores.

What this code does: It reads several scores on one line and converts them to a list of integers. It prints the highest, lowest, and average score, sorts the scores from high to low and prints the top three, and counts how many scores are at least 70.
scores = [int(s) for s in input("Enter scores separated by spaces: ").split()]
print("Scores:", scores)
print("Highest:", max(scores))
print("Lowest:", min(scores))
print("Average:", sum(scores) / len(scores))
scores.sort(reverse=True)
print("Top 3:", scores[:3])
passed = [s for s in scores if s >= 70]
print(f"{len(passed)} of {len(scores)} passed")

Try It: Remove Duplicates

The Program Input box is filled with milk eggs bread milk eggs butter. Click Run Code, then try a list of your own.

What this code does: It reads a line of items and builds a new list that keeps only the first copy of each item, in the original order. It reports how many duplicates were removed, sorts the unique items alphabetically, and joins them into one string with commas.
words = input("Enter items separated by spaces: ").split()
unique = []
for w in words:
    if w not in unique:
        unique.append(w)
print("Unique items:", unique)
print("Removed", len(words) - len(unique), "duplicates")
unique.sort()
print("Sorted:", unique)
print(", ".join(unique))

Common Mistakes with Lists

  • Assigning the result of sort(): items = items.sort() sets items to None, because sort(), append(), reverse(), and similar methods change the list in place and return None. Call the method on its own line, or use sorted().
  • IndexError: a list of 3 items has the indexes 0, 1, and 2, so items[3] fails. Use len(items) - 1 or items[-1] for the last item.
  • Thinking that b = a makes a copy: both names refer to the same list. Use a.copy() or a[:].
  • Using [[0] * 3] * 2 for a grid: the rows are the same list. Use [[0] * 3 for _ in range(2)].
  • Confusing append() and extend(): a.append([1, 2]) adds the list as one item, while a.extend([1, 2]) adds two items.
  • Removing items while looping over the list: the loop skips items because the positions shift. Loop over a copy, such as for x in items[:]:, or build a new list with a comprehension.
  • Calling remove() on a missing value: it raises a ValueError. Check with if x in items: first.
  • Calling pop() on an empty list: it raises an IndexError. Check that the list is not empty first.

Key Takeaways

  • A list is an ordered, mutable collection written with square brackets. It can hold mixed types and duplicates.
  • Indexes start at 0, negative indexes count from the end, and slices use [start:stop:step] with the stop position excluded.
  • Lists change in place. append(), insert(), extend(), remove(), pop(), del, and clear() add and remove items.
  • sort() sorts in place and returns None, while sorted() returns a new list.
  • b = a makes a second name for the same list. Use copy(), a slice, or copy.deepcopy() to make a copy.
  • List comprehensions build new lists from loops and filters in one line.
  • Nested lists store tables, and unpacking assigns list items to several variables at once.

Frequently Asked Questions

How do I create a list in Python?

Write the items inside square brackets separated by commas, for example colors = [“red”, “green”, “blue”]. An empty list is written []. You can also convert another iterable with list(), for example list(“abc”) or list(range(5)).

What is the difference between append() and extend() in Python?

The append() method adds its argument as one single item at the end of the list, so a.append([1, 2]) adds a list inside the list. The extend() method adds every item of an iterable separately, so a.extend([1, 2]) adds the two numbers 1 and 2.

How do I remove an item from a list in Python?

Use remove(value) to delete the first item with that value, pop(index) to remove an item by position and get it back, and del items[index] to delete by position. Use clear() to remove everything. A missing value in remove() raises a ValueError.

How do I copy a list in Python?

Use items.copy(), items[:], or list(items) to make a shallow copy. Writing b = a does not copy the list, it only gives it a second name. For lists that contain other lists, use copy.deepcopy() so that the inner lists are copied as well.

What is the difference between sort() and sorted() in Python?

The sort() method sorts the list in place and returns None. The sorted() function returns a new sorted list and leaves the original unchanged. Both accept reverse=True and a key function, for example key=len.

How do I find an item or its position in a list in Python?

Use the in operator to check whether a value is in the list, for example “red” in colors. Use index(value) to get the position of the first match, which raises a ValueError if the value is missing. Use count(value) to count how many times it appears.

What is the difference between a list and a tuple in Python?

A list is mutable, so you can add, remove, and change its items, and it is written with square brackets. A tuple is immutable, so it cannot be changed after it is created, and it is written with parentheses. Use a tuple for a fixed group of values and a list for a collection that changes.

How do I get the last item of a list in Python?

Use the negative index -1, for example items[-1]. For the last three items use the slice items[-3:]. The pop() method also returns the last item, but it removes it from the list.

Ready for the next step?Learn about tuples, the immutable cousin of lists.
Next: Tuples →