Skip to contentSkip to navigation

Module 03 · Lesson 01

Lists & Indexing Operations

Keep many values in order with lists: index and slice them, change them in place with append, insert, remove and pop, and sort them with sort() or sorted().

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Make and index lists
  • Slice a piece
  • Add, remove and sort
  • Watch a queue move

Many values, one name

A list keeps values in order under one name, and you can change it whenever you like.

  • Make one

    Square brackets and commas: pets = ["cat", "dog", "fish"].

  • Index

    pets[0] is the first item and pets[-1] the last. Counting starts at 0.

  • Change it

    append() adds to the end, insert() adds anywhere, remove() and pop() take items out.

  • Look inside

    len() counts the items, in checks for one, sorted() gives them in order.

Lists everywhere

Any time an app shows things in a row, there is probably a list behind it.

  • Up nextA music queue is a list: play [0], then take it off the front.
  • High scoresAdd the new score, sort the list, keep the top ten with a slice.
  • Shopping listsAdd items as you think of them and remove them as they go in the basket.
  • ChatsEach new message is appended to the end of the conversation.

Calling a list method

A method is a command that belongs to a value. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

list:The list you want to change. It must already exist, for example team = ["Ana"].

Build and change lists

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Make a list

Index 0 is the first item, -1 the last.

Your turn: Print the second pet using a positive index, then using a negative one.

Python
pets = ["cat", "dog", "fish", "rabbit"]
print(pets)
print(len(pets), "pets")
print("First:", pets[0])
print("Last:", pets[-1])
Output
Press Run to see what it prints.

Watch a queue move

Press Step to run one line at a time. Watch the list in the names box grow and shrink.

Ready. Press Step to run the first line.

  1. queue = ["Ana", "Ben"]
  2. queue.append("Cy")
  3. first = queue.pop(0)
  4. queue.insert(0, "Dee")
  5. print(first, "is served")
  6. print(queue)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Counting from the end: what prints?

nums = [10, 20, 30]
print(nums[-2])

0 of 6 answered

Common list misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Ordered collections you can change

A list is an ordered collection of values written inside square brackets and separated by commas. The values, called items or elements, can be of any type, and a list can be empty.

Try it 1: edit me, then Run
scores = [70, 85, 92]
names = ["Ana", "Bo", "Cy"]
mixed = [3, "three", 3.0, True]
empty = []
print(len(scores))
Output
Press Run to see what it prints.

len() returns how many items a list has, here 3.

Indexes

Each item has a position called its index, and counting starts at 0. The first item is scores[0] and the last is scores[len(scores) - 1]. Python also counts from the end with negative indexes: scores[-1] is the last item and scores[-2] the one before it. Asking for an index that does not exist, such as scores[3] in a three-item list, raises IndexError: list index out of range.

Try it 2: edit me, then Run
scores = [70, 85, 92]
print(scores[0], scores[-1])
Output
Press Run to see what it prints.

Slices

A slice takes part of a list and returns a new list: items[start:stop] from start up to but not including stop, just like range(). Either end can be left out, and an optional third number is a step.

Try it 3: edit me, then Run
letters = ["a", "b", "c", "d", "e"]
print(letters[1:3])    # ['b', 'c']
print(letters[:2])     # ['a', 'b']
print(letters[2:])     # ['c', 'd', 'e']
print(letters[::2])    # ['a', 'c', 'e']
print(letters[::-1])   # reversed copy
Output
Press Run to see what it prints.

Slicing never raises an error for positions past the end; it simply returns what exists.

Changing a list

Unlike strings, lists are mutable: you can change them after creating them. Assigning to an index replaces that item, and several methods change the list itself.

Try it 4: edit me, then Run
basket = ["bread", "milk"]
basket[1] = "oat milk"        # replace an item
basket.append("eggs")         # add one item to the end
basket.insert(0, "jam")       # add at a position
basket.extend(["tea", "rice"])# add every item of another list
basket.remove("bread")        # remove the first matching value
last = basket.pop()           # remove and return the last item
print(basket, last)
Output
Press Run to see what it prints.

This prints ['jam', 'oat milk', 'eggs', 'tea'] rice. pop() with no argument removes the last item; pop(0) removes the first. remove() raises ValueError if the value is not in the list, so check with in first when you are not sure.

Methods such as append() change the list in place and return None. Writing basket = basket.append("eggs") therefore replaces your list with None, a very common mistake. Call the method on its own line.

The + operator is different: items + [4] builds a new list and leaves items unchanged. * repeats a list: [0] * 3 is [0, 0, 0].

Looking inside

in tests membership, index() finds the position of a value, count() counts it, and the built-in functions min(), max() and sum() work on lists of numbers.

Try it 5: edit me, then Run
temps = [18, 22, 19, 22]
print(22 in temps, temps.index(22), temps.count(22))
print(min(temps), max(temps), sum(temps) / len(temps))
Output
Press Run to see what it prints.

Lists and loops

Lists and for loops belong together. Looping over a list visits every item in order, and the accumulator pattern from the loops lessons works with lists too: start with an empty list and append() to it. That is how you build a new list from an old one, for example keeping only some items.

Try it 6: edit me, then Run
prices = [4.5, 12.0, 3.25, 20.0]
cheap = []
for price in prices:
    if price < 10:
        cheap.append(price)
print(cheap)              # [4.5, 3.25]
Output
Press Run to see what it prints.

Building a new list like this is safer than removing items from the list you are looping over. Removing while looping shifts the remaining items left, so the loop skips the one that moved into the gap. When you need to drop items, build a new list of the ones you keep, or loop over a copy. A later course shows list comprehensions, a one-line way to write this same pattern.

Sorting: sort() or sorted()

There are two ways to sort, and choosing the right one matters.

  • items.sort() sorts the list in place. The original order is gone, and the method returns None.
  • sorted(items) returns a new sorted list and leaves the original alone. It works on any iterable, including strings.
Try it 7: edit me, then Run
scores = [4, 2, 3]
ranked = sorted(scores)
print(ranked, scores)     # [2, 3, 4] [4, 2, 3]
scores.sort(reverse=True)
print(scores)             # [4, 3, 2]
Output
Press Run to see what it prints.

Both accept reverse=True for largest first, and key= to sort by something other than the value itself. sorted(words, key=len) sorts words by length. Use sorted() when you still need the original order; use .sort() when you do not, and never assign its result.

Sorting a list that mixes numbers and strings raises TypeError, because Python cannot order them. Strings sort in dictionary order with capital letters first.

Two names, one list

Assignment never copies a list. After other = items, both names refer to the same list, so a change through one name is visible through the other.

Try it 8: edit me, then Run
items = ["pen", "book"]
other = items
other.append("cup")
print(items)              # ['pen', 'book', 'cup']
copy = items.copy()       # or items[:] or list(items)
copy.append("ink")
print(items)              # unchanged
Output
Press Run to see what it prints.

This is the "labels, not boxes" idea from the variables lesson. With numbers it rarely matters because numbers cannot be changed in place; with lists it matters a lot. When you want an independent list, make a copy with .copy().

Syntax

The general shape of the statements in this lesson.

syntax.py
items = [1, 2, 3]       len(items)
items[0]  items[-1]     # first, last
items[1:3]  items[::-1] # slice, reversed copy
items.append(x)  items.insert(i, x)  items.extend(more)
items.remove(x)  items.pop()  items.pop(i)
x in items   items.index(x)   items.count(x)
items.sort()            # in place, returns None
sorted(items)           # new list; reverse=True, key=len
copy = items.copy()
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A top three leaderboard

Beginner

Given a list of scores, print the top three from highest to lowest without changing the original list, then show the original is untouched.

Python
scores = [56, 91, 73, 88, 64, 91]
top = sorted(scores, reverse=True)[:3]
print("Top three:", top)
print("Original:", scores)
print("Best score appears", scores.count(91), "times")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

sorted(..., reverse=True) returns a new list from highest to lowest, and the slice [:3] keeps the first three items of that new list. Because sorted() never changes its input, scores keeps its original order, which matters if the order means something, such as the round each score came from.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Assigning the result of a method

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
numbers = [3, 1, 2]
numbers = numbers.sort()
print(numbers)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints None

Write this instead

numbers = [3, 1, 2]
numbers.sort()
print(numbers)

Why it happens

sort() changes the list in place and returns None, and that None is then stored in numbers.

In the real world

Where this shows up in software people use every day.

  1. A class reading log

    Education

    A teacher keeps the minutes each pupil read this week in a list, then reports the average, the range and the three longest sessions without losing the register order.

    Why Python fits

    Built-in functions answer the summary questions in one line each, and sorted() produces a ranking while the list itself stays in the same order as the class register.

    Python
    minutes = [25, 40, 15, 60, 30, 45]
    average = sum(minutes) / len(minutes)
    print(f"Average: {average:.1f} min")
    print(f"Shortest {min(minutes)}, longest {max(minutes)}")
    print("Longest three:", sorted(minutes, reverse=True)[:3])
    print("Register order kept:", minutes)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Can a list hold different types?

Yes, but most real lists hold one kind of value, such as all numbers or all names. That makes them easier to sort, sum and loop over.

What is the difference between append and extend?

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

How do I sort names ignoring capital letters?

Pass a key: sorted(names, key=str.lower) compares lowercase versions while keeping the original spelling.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.