Skip to main content

Programming fundamentals · Beginner · 15 min

Index, slice, sort and search lists in Python

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will use a list of market prices to practise indexing, slicing, adding and removing items, searching, sorting and a first list comprehension, and end with a script that answers five questions about the prices.

On this page

A list is Python's everyday container: one name that holds many values in order. Shopping lists, scores, readings from a sensor and the prices on a market stall all fit in a list. Knowing a handful of list operations well saves you from writing long loops for things Python already does in one line.

In this tutorial you work with one list of market prices throughout. You pick out single prices by position, cut out ranges, add and remove prices, check whether a price is there, put the prices in order and work out what each costs with tax. Each step is a small script you run, so you see every result yourself. At the end you write one script that answers five questions about the price list.

If you followed the budget tracker series, you have already stored expenses in a list in store expenses in a list and show a summary. That tutorial is about collecting items; this one is the toolkit for working with a list once you have it.

The examples use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app can install Python with pkg install python; nothing here downloads anything, so after the install every step runs offline and uses no mobile data. Prices are whole numbers in your own currency: read them as naira, shillings, rand or cedis, whatever you pay with.

Step 1 · Pick out items by position

Make a folder for this tutorial and check your Python version:

Bash
mkdir -p ~/lists-demo
cd ~/lists-demo
python3 --version

Now write a script that creates the price list and reads single items from it:

Bash
cat > index.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600]

print(len(prices))
print(prices[0])
print(prices[2])
print(prices[-1])
print(prices[-2])
print(prices[len(prices) - 1])
PY
python3 index.py

The cat > index.py <<'PY' line writes everything up to the closing PY into index.py; you can paste the lines between them into your editor instead. In the script:

  • prices = [...] makes a list. Square brackets hold the items, separated by commas.
  • len(prices) counts the items.
  • prices[0] reads the item at position 0. The position number is called an index, and Python counts from 0, so the first item is [0] and the third is [2].
  • prices[-1] counts from the other end: -1 is the last item, -2 the one before it. You do not need to know how long the list is.
  • prices[len(prices) - 1] is the long way to reach the last item. It gives the same answer as prices[-1], which is why nobody writes it.

Check it worked

The output is six lines: 6, 450, 300, 600, 2000 and 600. The first and last item are positions 0 and -1; if you got 1200 for prices[0], you counted from 1.

Step 2 · See what an IndexError looks like

Ask for a position that does not exist and Python stops with an error. Try it with a three-item list, where the last index is 2:

Bash
python3 -c 'prices = [450, 1200, 300]; print(prices[3])' || echo "exit status $?"

python3 -c runs the code in quotes without a file. The || echo "exit status $?" part prints the exit status when the command fails, so you can see that the program ended with an error rather than finishing.

Check it worked

Python prints a traceback that ends with IndexError: list index out of range, and the shell prints exit status 1. A list of length 3 has indexes 0, 1 and 2 (or -1, -2 and -3). Asking for [3] is the most common off-by-one mistake: the length is one more than the last index.

Step 3 · Cut out ranges with slices

A slice gives you a new list made of part of the old one. Write [start:stop]: the item at start is included, the item at stop is not. Add a third number, [start:stop:step], to take every second or third item:

Bash
cat > slices.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600]

print(prices[1:4])
print(prices[:3])
print(prices[3:])
print(prices[-2:])
print(prices[::2])
print(prices[1::2])
print(prices[::-1])
print(prices[4:100])
print(prices[10:])
PY
python3 slices.py

Line by line:

  • prices[1:4] takes positions 1, 2 and 3. Stop is left out, so you get 4 - 1 = 3 items.
  • prices[:3] leaves out start, which means "from the beginning": the first three prices.
  • prices[3:] leaves out stop, which means "to the end": everything from position 3.
  • prices[-2:] starts two from the end: the last two prices.
  • prices[::2] takes the whole list in steps of 2: positions 0, 2 and 4.
  • prices[1::2] starts at 1 with the same step: positions 1, 3 and 5.
  • prices[::-1] steps backwards, which reverses the list.
  • prices[4:100] and prices[10:] reach past the end. Slices never raise IndexError; they return whatever items fall in the range, which can be none.

Check it worked

The output is:

Text
[1200, 300, 850]
[450, 1200, 300]
[850, 2000, 600]
[2000, 600]
[450, 300, 2000]
[1200, 850, 600]
[600, 2000, 850, 300, 1200, 450]
[2000, 600]
[]

Every line is in square brackets, because a slice is always a list, even when it holds one item or none. Compare that with indexing: prices[0] is 450, but prices[0:1] is [450].

Step 4 · Add and remove prices

Lists can change after you create them. These methods (functions that belong to the list, called with a dot) change the list in place:

Bash
cat > change.py <<'PY'
prices = [450, 1200, 300, 850]

prices.append(700)
print(prices)

prices.insert(1, 250)
print(prices)

prices.remove(300)
print(prices)

last = prices.pop()
print(last, prices)

first = prices.pop(0)
print(first, prices)
PY
python3 change.py
  • append(700) adds 700 to the end.
  • insert(1, 250) puts 250 at position 1 and moves everything after it one place along.
  • remove(300) deletes the first item equal to 300. You give it a value, not a position.
  • pop() takes the last item out of the list and hands it back, so you can store it in last.
  • pop(0) does the same for position 0, the first item.

Check it worked

The output is:

Text
[450, 1200, 300, 850, 700]
[450, 250, 1200, 300, 850, 700]
[450, 250, 1200, 850, 700]
700 [450, 250, 1200, 850]
450 [250, 1200, 850]

Each line shows the list after the change above it, so you can follow the list growing and shrinking.

When adding and removing goes wrong

Three mistakes stop beginners here. The script below makes each one on purpose. try and except catch the error so the script carries on and prints the message instead of stopping:

Bash
cat > mistakes.py <<'PY'
prices = [450, 1200]

try:
    prices.remove(999)
except ValueError as err:
    print("ValueError:", err)

prices.clear()
try:
    prices.pop()
except IndexError as err:
    print("IndexError:", err)

try:
    prices[0] = 500
except IndexError as err:
    print("IndexError:", err)
PY
python3 mistakes.py
  • remove(999) fails with ValueError because 999 is not in the list.
  • clear() empties the list, and pop() on an empty list fails with IndexError: there is nothing to take.
  • prices[0] = 500 replaces the item at position 0, which works on a list that has one. On an empty list there is no position 0, so it fails too. To add an item, use append, not an index.

The output is three lines, each starting with the error type and followed by Python's message, something like ValueError: list.remove(x): x not in list, IndexError: pop from empty list and IndexError: list assignment index out of range.

Step 5 · Check whether a price is on the list

in asks "is this value somewhere in the list?" and answers True or False. Two more methods tell you where it is and how often it appears:

Bash
cat > search.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600, 300]

print(300 in prices)
print(999 in prices)
print(999 not in prices)
print(prices.index(300))
print(prices.count(300))

wanted = 999
if wanted in prices:
    print("found at position", prices.index(wanted))
else:
    print(wanted, "is not in the list")
PY
python3 search.py
  • 300 in prices is True; 999 in prices is False. not in is the opposite test.
  • prices.index(300) gives the position of the first 300, which is 2. The second 300 at position 6 is ignored.
  • prices.count(300) counts how many times 300 appears.
  • index raises ValueError for a value that is not there, like remove does. The if wanted in prices: check at the end avoids that: look first, then ask for the position.

Check it worked

The output is True, False, True, 2, 2 and then 999 is not in the list. Change wanted = 999 to wanted = 850 and run the script again: the last line becomes found at position 3.

in checks the items one by one from the start, which is fine for a few thousand prices. For very long sorted lists there is a faster way, covered in search a list with linear and binary search.

Step 6 · Put prices in order

Python has two ways to sort, and mixing them up is a classic bug. sorted(prices) makes a new, sorted list and leaves the original alone. prices.sort() sorts the list itself and returns nothing:

Bash
cat > sorting.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600]

cheapest_first = sorted(prices)
print(cheapest_first)
print(prices)

print(sorted(prices, reverse=True))

result = prices.sort()
print(result)
print(prices)

print(min(prices), max(prices), sum(prices))
PY
python3 sorting.py
  • sorted(prices) returns a new list in ascending order, stored in cheapest_first. Printing prices straight after shows it has not changed.
  • reverse=True sorts from highest to lowest.
  • prices.sort() reorders prices itself. Its return value is None, Python's "no value", so result holds None.
  • min, max and sum give the smallest price, the largest and the total, without sorting at all.

Check it worked

The output is:

Text
[300, 450, 600, 850, 1200, 2000]
[450, 1200, 300, 850, 2000, 600]
[2000, 1200, 850, 600, 450, 300]
None
[300, 450, 600, 850, 1200, 2000]
300 2000 5400

The None line is the bug to remember. If you write prices = prices.sort(), the list is sorted and then thrown away, and prices becomes None. Use sorted() when you want to keep the original order as well, and .sort() when you do not.

Step 7 · Add tax with a list comprehension

To make a new list where every price has tax added, you could write a loop that appends to an empty list. A list comprehension does the same in one line. This example uses a 7.5% tax rate; change TAX_RATE to the rate where you live:

Bash
cat > tax.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600]
TAX_RATE = 0.075

with_tax = [round(price * (1 + TAX_RATE), 2) for price in prices]
print(with_tax)

under_1000 = [price for price in prices if price < 1000]
print(under_1000)
PY
python3 tax.py

Read the comprehension from the middle outwards:

  • for price in prices takes each price in turn.
  • round(price * (1 + TAX_RATE), 2) is what goes into the new list for that price: the price times 1.075, rounded to 2 decimal places.
  • The square brackets around the whole thing collect the results into a new list. prices itself is unchanged.
  • TAX_RATE is in capitals by convention, to show it is a setting you do not change while the program runs.
  • The second comprehension adds if price < 1000 at the end, which keeps only the prices that pass the test. Nothing is calculated, so the prices go in as they are.

Check it worked

The first line is [483.75, 1290.0, 322.5, 913.75, 2150.0, 645.0] and the second is [450, 300, 850, 600]. The prices with tax are floats (numbers with a decimal point), so 1200 becomes 1290.0, not 1290. The second list has four prices, all below 1000, in their original order.

Step 8 · Answer five questions about the prices

Put everything together. This script takes a longer price list and answers five questions a stall holder might ask:

Bash
cat > answers.py <<'PY'
prices = [450, 1200, 300, 850, 2000, 600, 300, 1500]
TAX_RATE = 0.075

ordered = sorted(prices)

print("1. Cheapest and dearest:", ordered[0], "and", ordered[-1])
print("2. Three cheapest:", ordered[:3])

wanted = 850
if wanted in prices:
    print("3.", wanted, "is on the list at position", prices.index(wanted))
else:
    print("3.", wanted, "is not on the list")

cheap = [price for price in prices if price < 1000]
print("4. Under 1000:", len(cheap), "of", len(prices))

with_tax = [price * (1 + TAX_RATE) for price in prices]
print("5. Total with tax:", round(sum(with_tax), 2))
PY
python3 answers.py

Each answer uses one tool from this tutorial:

  1. sorted once, then index [0] and [-1] on the sorted copy for the cheapest and dearest.
  2. A slice [:3] of the sorted copy for the three cheapest.
  3. in to check first, then index for the position, so a missing price cannot cause a ValueError.
  4. A comprehension with if to keep the cheap prices, and len to count them.
  5. A comprehension to add tax to every price, then sum and round once at the end, so rounding happens on the total rather than on each price.

Check it worked

The output is:

Text
1. Cheapest and dearest: 300 and 2000
2. Three cheapest: [300, 300, 450]
3. 850 is on the list at position 3
4. Under 1000: 5 of 8
5. Total with tax: 7740.0

The three cheapest include 300 twice, because the list holds it twice. prices is still in its original order, which is why the position in answer 3 is 3 and not its place in the sorted list. Change the prices or wanted and run it again: every answer updates without any other edit.

When you have finished, delete the demo folder:

Bash
cd ~
rm -rf ~/lists-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.