Python Tutorial › Data Structures › Lists

Python Lists

BeginnerLesson 18 of 4712 min read11 runnable examples

A list stores many values in one variable, in order. You will use lists in almost every Python program you write, from a shopping cart to a set of test results.

Advertisement
In this lesson
  • Create lists of any type
  • Read items with indexing and slicing
  • Add, change and remove items
  • Loop through a list
  • Sort a list two ways
  • Avoid the shared-list copy bug

What is a list in Python?

A list is written with square brackets, with items separated by commas. One list can hold numbers, strings, booleans, None and even other lists.

Python
fruits = ["apple", "banana", "cherry"]mixed = [1, "two", 3.0, True, None]empty = [] print(fruits)print(type(fruits))print(len(mixed), len(empty))
Output
['apple', 'banana', 'cherry']
<class 'list'>
5 0
Note

Lists are ordered (items keep their position), mutable (you can change them after creating them) and they allow duplicates.

You can also build a list from any iterable with list(), for example from a string or a range.

Python
print(list("abc"))print(list(range(1, 6)))
Output
['a', 'b', 'c']
[1, 2, 3, 4, 5]

Indexing and slicing

Every item has a position, called its index. Counting starts at 0 from the left and at -1 from the right.

Python
nums = [10, 20, 30, 40, 50] print(nums[0])      # first itemprint(nums[-1])     # last itemprint(nums[1:4])    # items at index 1, 2, 3print(nums[::-1])   # reversed copy
Output
10
50
[20, 30, 40]
[50, 40, 30, 20, 10]
Tip

A slice nums[start:stop] includes start but stops before stop. That is why nums[1:4] returns three items. Leave out start or stop to go from the beginning or to the end.

Reading an index that does not exist raises an IndexError. A slice never does: it just returns fewer items.

Python
nums = [10, 20, 30]print(nums[1:10])print(nums[5])
Output
[20, 30]
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(nums[5])
          ~~~~^^^
IndexError: list index out of range

Add, change and remove items

Python
cart = ["pen", "book"] cart.append("bag")        # add to the endcart.insert(1, "ink")     # add at index 1cart[0] = "pencil"        # replace an itemprint(cart) last = cart.pop()         # remove and return the last itemprint(last, cart) cart.remove("ink")        # remove by valueprint(cart)
Output
['pencil', 'ink', 'book', 'bag']
bag ['pencil', 'ink', 'book']
['pencil', 'book']

Python list methods you will use most

MethodWhat it doesReturns
append(x)Adds x to the endNone
insert(i, x)Adds x before index iNone
extend(items)Adds every item from another iterableNone
remove(x)Removes the first x; raises ValueError if it is missingNone
pop(i=-1)Removes the item at index ithe removed item
index(x)Finds the position of the first xint
count(x)Counts how often x appearsint
sort() / reverse()Reorders the list in placeNone
clear()Removes every itemNone
copy()Makes a shallow copya new list

append() adds its argument as one item, while extend() adds each item separately:

Python
a = [1, 2]a.append([3, 4])print(a) b = [1, 2]b.extend([3, 4])print(b)
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]

Loop through a list

A for loop visits each item in order. enumerate() gives you the position and the item together, so you do not need a counter variable.

Python
tasks = ["write tests", "run tests", "fix bugs"] for number, task in enumerate(tasks, start=1):    print(f"{number}. {task}")
Output
1. write tests
2. run tests
3. fix bugs

Use in to check whether a value is in a list:

Python
browsers = ["chromium", "firefox", "webkit"]print("firefox" in browsers)print("edge" in browsers)
Output
True
False

Sort a list

Python
scores = [72, 95, 58, 88] print(sorted(scores))          # new sorted listprint(scores)                  # original is unchanged scores.sort(reverse=True)      # sorts in placeprint(scores)
Output
[58, 72, 88, 95]
[72, 95, 58, 88]
[95, 88, 72, 58]
Watch out

scores.sort() changes the list and returns None. Writing scores = scores.sort() throws your list away. Use sorted(scores) when you need a new list.

Pass key= to sort by something other than the value itself, such as the length of each word:

Python
words = ["banana", "fig", "apple"]print(sorted(words, key=len))
Output
['fig', 'apple', 'banana']

Copy a list without surprises

Assigning a list to a new name does not copy it. Both names point at the same list, so a change through one name shows up in the other.

Python
a = [1, 2]b = a            # b is the SAME list, not a copyb.append(3)print(a) c = a.copy()     # c is a new listc.append(4)print(a, c)
Output
[1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

Check your understanding

Predict the output

x = [1, 2, 3]y = x * 2print(y, len(y))

Quick quiz

1. What does [10, 20, 30][-1] return?

2. Which call removes and returns the last item?

3. After b = a and b.append(3), what is in a?

4. What does [3, 1, 2].sort() evaluate to?

Exercise: remove duplicate emails

You have a list of signup emails with repeats. Build a list that keeps each email once, in the order it first appeared.

Input
["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
Expected output
['a@x.com', 'b@x.com', 'c@x.com']
Hint 1

A set removes duplicates but does not keep the order.

Hint 2

Dictionary keys are unique and keep insertion order.

Program Practice: Python list programs

Practise what you just learned. Start with the easy programs and work up.

Python lists FAQ

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

A list is mutable, so you can add, change and remove items. A tuple is immutable: once created, its items cannot change. Use a tuple for fixed data such as coordinates. See List vs Tuple.

How do I check if an item is in a list?

Use the in operator: "apple" in fruits returns True or False.

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

append(x) adds x as one item, even if x is a list. extend(items) adds each item of items separately.

How do I remove duplicates from a list and keep the order?

Use list(dict.fromkeys(items)). list(set(items)) also removes duplicates but does not keep the original order.

Can a Python list hold different data types?

Yes. A list can mix integers, strings, floats, booleans, None and other lists, although lists of one type are easier to work with.

1 thought on “Python Lists”

Leave a Comment