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(), andindex(). - 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.
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)))colors refers to a list of three strings. Their indexes are 0, 1, and 2.[] is a list with no items. It is often used as a starting point that is filled later.colors[0] is the first item and colors[-1] counts from the end, so it is the last item. The output is red blue.len() counts the items. The output is 3 4 0.in operator checks whether a value is one of the items. The output is True False.list("abc") splits the string into its characters, and list(range(3)) turns the range into a list. The output is ['a', 'b', 'c'] [0, 1, 2].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.
[:] 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)10 is at index 0 and 60 is at index 5.nums[1:4] takes the positions 1, 2, and 3. The output is [20, 30, 40].nums[:2] is everything before position 2, and nums[4:] is everything from position 4 on. The output is [10, 20] [50, 60].nums[::2] takes the positions 0, 2, and 4. The output is [10, 30, 50].nums[::-1] walks through the whole list backwards. The output is [60, 50, 40, 30, 20, 10].nums[-3:] starts three items from the end. The output is [40, 50, 60].nums[:] slices the whole list, which creates a new list with the same items.== compares the contents, so it is True. is asks whether both names refer to the very same object, and they do not. The output is True False.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.
pets = ["cat", "dog", "fish"]
pets[1] = "hamster"
print(pets)
pets[1:3] = ["rabbit", "bird", "turtle"]
print(pets)
alias = pets
alias[0] = "lion"
print(pets)pets refers to a list of three strings."dog" with "hamster" in the same list.['cat', 'hamster', 'fish'].pets[1:3] covers positions 1 and 2. Those two items are replaced by the three new items, so the list grows by one.['cat', 'rabbit', 'bird', 'turtle'].alias = pets does not copy the list. It gives the same list a second name.alias changes the list that pets sees as well.['lion', 'rabbit', 'bird', 'turtle'].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 positioniand 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 equalsx. It raises aValueErrorif there is none.pop()removes and returns the last item, andpop(i)does the same for positioni. It raises anIndexErroron an empty list.del items[i]deletes by position, anddel 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.
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)["a", "b"]."c" at the end. The list is ["a", "b", "c"].insert(0, "z") puts "z" at position 0 and moves the others one place to the right. The list is ["z", "a", "b", "c"].extend() adds each item of the given list separately. The list is ["z", "a", "b", "c", "d", "e"].['z', 'a', 'b', 'c', 'd', 'e']."b". The list is ["z", "a", "c", "d", "e"].pop() removes the last item, "e", and returns it, so it is stored in last.pop(0) removes and returns the first item, "z", which is stored in first. The list is now ["a", "c", "d"].['a', 'c', 'd'] e z.del items[0] deletes the first item, "a", and returns nothing.['c', 'd'].clear() removes every item but keeps the list itself.[].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.
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)data holds five numbers, and the value 2 appears twice.9 is at index 2, and 2 appears 2 times. The output is 2 2.sorted(data) returns a sorted copy, while data itself is untouched. The output is [2, 2, 5, 7, 9] [5, 2, 9, 2, 7].data.sort() rearranges the list itself, from the smallest to the largest value.[2, 2, 5, 7, 9].reverse=True sorts from the largest to the smallest value.[9, 7, 5, 2, 2].reverse() turns the list around in place. It does not sort.[2, 2, 5, 7, 9].2 9 25.words holds three strings of different lengths: 6, 4, and 5 characters.key=len tells sort() to compare the lengths of the words instead of the words themselves. Do not add parentheses after len.['kiwi', 'apple', 'banana'].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.
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)a holds three numbers.b holds two numbers.a followed by the items of b. The output is [1, 2, 3, 4, 5].b * 3 repeats the items three times. The output is [4, 5, 4, 5, 4, 5].[0, 0, 0, 0].n in a, the value n ** 2 is collected into a new list.[1, 4, 9].n % 2 == 1 is true are kept.[1, 3, 5, 7, 9].enumerate() gives pairs of an index and an item, which the loop unpacks into i and value.0 1, 1 2, and 2 3.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.
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)grid holds three rows, and each row is a list of three numbers.grid[1] is the second row [4, 5, 6], and [2] picks its third item. The output is 6.row is one whole row on each repetition.6, 15, and 24.[1, 4, 7].first and second. The starred variable rest collects all the remaining items into a list.10 20 [30, 40].1 to a and 2 to b.(2, 1), and then assigned to a and b. No temporary variable is needed.2 1.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.
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)copy module provides deepcopy().original holds two inner lists.copy() creates a new outer list, but it holds the very same two inner lists.deepcopy() copies the outer list and every inner list as well.original. The shallow copy shares that inner list, and the deep copy does not.[[99, 2], [3, 4]].[[1, 2], [3, 4]].row is the list [0, 0, 0].[row] * 2 does not copy the row. It puts the same list in the table twice.[[1, 0, 0], [1, 0, 0]].[0] * 3 once per row, so every row is a separate list. The name _ signals that the loop variable is not used.[[1, 0, 0], [0, 0, 0]].Tip: Appending to the end of a list withappend()is fast, but inserting or removing at the beginning, and searching withinorindex(), 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.
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")input() reads the line, split() cuts it into five words, and the comprehension converts each word with int(). The result is the list [85, 92, 78, 90, 66].Scores: [85, 92, 78, 90, 66].Highest: 92.Lowest: 66.Average: 82.2.[92, 90, 85, 78, 66].[:3] takes the first three items of the sorted list. The output is Top 3: [92, 90, 85].len(passed) is 4 and len(scores) is 5. The output is 4 of 5 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.
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))split() turns the line into a list of six words: ["milk", "eggs", "bread", "milk", "eggs", "butter"].unique starts empty and will collect each item once.w takes each word in turn.w not in unique is true when the word has not been added yet. It is true for the first milk and false for the second one.unique, which keeps the original order.Unique items: ['milk', 'eggs', 'bread', 'butter'].Removed 2 duplicates.sort() puts the list in alphabetical order, in place.Sorted: ['bread', 'butter', 'eggs', 'milk'].", ".join(unique) builds one string from the list, with a comma and a space between the items. The output is bread, butter, eggs, milk.Common Mistakes with Lists
- Assigning the result of
sort():items = items.sort()setsitemstoNone, becausesort(),append(),reverse(), and similar methods change the list in place and returnNone. Call the method on its own line, or usesorted(). - IndexError: a list of 3 items has the indexes 0, 1, and 2, so
items[3]fails. Uselen(items) - 1oritems[-1]for the last item. - Thinking that
b = amakes a copy: both names refer to the same list. Usea.copy()ora[:]. - Using
[[0] * 3] * 2for a grid: the rows are the same list. Use[[0] * 3 for _ in range(2)]. - Confusing
append()andextend():a.append([1, 2])adds the list as one item, whilea.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 aValueError. Check withif x in items:first. - Calling
pop()on an empty list: it raises anIndexError. 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, andclear()add and remove items. sort()sorts in place and returnsNone, whilesorted()returns a new list.b = amakes a second name for the same list. Usecopy(), a slice, orcopy.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.