Learn by reading through in order

How to Use Python Lists (list)

Get the Python list type under your fingers in the browser — from indexing and slicing to the methods you reach for daily.

Creating a list

With a list (list), you can hold several values together in one place. Unlike int or str, where a variable holds a single value, a list can line up any number of values side by side.

You declare one by wrapping values in [ and ], separated by commas.

A list's contents and their indices
102030400123

Just like with strings, you access items by 0-based index. [0] gives you the first, and [-1] gives you the last.

A key feature of lists is that you can change the values afterward.

# Declaring a list
numbers = [10, 20, 30, 40]

# Empty list (to be filled in later)
empty = []

# Access
print(numbers[0])     # 10
print(numbers[-1])    # 40

# Overwrite
numbers[1] = 99
print(numbers)        # [10, 99, 30, 40]

# Mixed types are fine
mixed = [1, "apple", 3.14, True]
print(mixed[1])       # apple

Nested lists (lists inside lists)

You can also put lists inside a list, like [[1, 2], [3, 4]]. To pull a value out, you chain two indices as in data[1][0]. It's handy for table-shaped data, but a plain flat list is plenty while you're getting started.

Let's work with a shopping list of fruits.

① Create fruits = ["apple", "banana", "grape", "lemon"], then print() the first and last items.

② Replace fruits[1] with "orange" and print() the whole list.

Python Editor

Run code to see output

Slicing

Lists use the same slice syntax as strings. [start:end] gives a sub-list, [::step] steps through the list, and [-n:] grabs the last n items.

The result of a slice is a list.

How slicing works
[1,2,3,4,5][:3][1, 2, 3]first 3[1,2,3,4,5][-2:][4, 5]last 2slicetakeslicetake

[:3] takes the first 3 (half-open, doesn't include end), and [-2:] takes the last 2.

It works exactly like string slicing.

nums = [1, 2, 3, 4, 5]

print(nums[:3])    # [1, 2, 3]
print(nums[2:])    # [3, 4, 5]
print(nums[-2:])   # [4, 5]
print(nums[::2])   # [1, 3, 5] (every other one)

# The original list doesn't change (a new list is returned)
print(nums)        # [1, 2, 3, 4, 5]

You're given scores = [72, 85, 91, 68, 77, 95].

① Use a slice to pull out the first 3 ([72, 85, 91]) and print them.

② Use a slice to pull out the last 2 ([77, 95]) and print them.

Python Editor

Run code to see output

Adding and removing items

Lists come with plenty of methods to add or remove items. These methods change the list itself. In other words, calling list.append(...) modifies list in place.

MethodWhat it does
append(x)Add one item to the end
extend(iterable)Append all items of another list to the end
insert(i, x)Insert x at position i
remove(x)Scan from the left and remove the first match of x
pop(i)Remove the item at position i and return it (defaults to the last)
clear()Empty out the whole list
append vs extend
[1, 2, 3].append([4, 5])[1,2,3,[4,5]]nested[1, 2, 3].extend([4, 5])[1,2,3,4,5]flattenedcallresultcallresult

append adds "one element".

extend "unpacks and adds" each item.

Even with the same [4, 5] you pass in, the result is different.

box = [1, 2, 3]

# Add
box.append("apple")       # add one to the end
print(box)                # [1, 2, 3, 'apple']

box.extend(["banana", "grape"])  # unpack and append at the end
print(box)                # [1, 2, 3, 'apple', 'banana', 'grape']

box.insert(1, "NEW")      # insert at index 1
print(box)                # [1, 'NEW', 2, 3, 'apple', 'banana', 'grape']

# Remove
box.remove("apple")       # remove the first match by value
print(box)                # [1, 'NEW', 2, 3, 'banana', 'grape']

v = box.pop(0)            # take out index 0 and return it
print(v)                  # 1
print(box)                # ['NEW', 2, 3, 'banana', 'grape']

remove / pop on something that's not there → error

remove(x) raises ValueError if x isn't in the list, and pop(i) raises IndexError if i is out of range. A safe pattern is to check for presence first with if x in box: before removing.

Let's edit a To-Do list.

You start with todo = ["shopping", "gym"].

① Use append to add "reading" to the end.

② Use extend to add ["walk", "study"] to the end all at once.

③ Use insert to drop "breakfast" at the front.

④ Use remove to delete "gym", then print() the final list.

Python Editor

Run code to see output

Sorting and searching (sort / reverse / count / index)

Lists also have sorting and searching methods. The important thing here is that there are two kinds of methods.

- Methods that modify the list (sort / reverse) → don't capture a return value; the list itself changes

- Methods that return a value (count / index) → use the return value, as in print(list.count(...))

Modifies vs returns
sort()reverse()list.sort()(no return)the listchangescount()index()n = list.count(x)capturethe resultusageside effectusagereturn

sort / reverse: modify the list directly. Don't capture.

count / index: don't touch the list — they return a value. Capture it and use it.

fruits = ["banana", "lemon", "apple", "grape"]

# (1) Modifying methods: the list changes just by calling them
fruits.sort()
print(fruits)          # ['apple', 'banana', 'grape', 'lemon']

fruits.reverse()
print(fruits)          # ['lemon', 'grape', 'banana', 'apple']

# (2) Returning methods: capture and use the return value
nums = [1, 2, 2, 3, 2, 4]
print(nums.count(2))   # 3 (there are three 2s)
print(nums.index(3))   # 3 (3 is the 4th item = index 3)

Why print(fruits.sort()) prints None

A common mistake: writing print(fruits.sort()) and seeing None printed. sort() doesn't return a value — it sorts fruits in place.

The right fix is to call fruits.sort() on its own, then print(fruits) on the next line — split it into two lines.

By the way, the details of return values (the values that methods and functions hand back) will be covered in the articles on functions and object-oriented programming. For now, it's enough to remember the two patterns: "sort / reverse change the list just by being called" and "count / index are captured with = and then used".

Let's analyze a list of test scores: scores = [72, 85, 91, 68, 77, 95, 85].

① Use sort() to sort ascending, then print() the sorted list.

② Use count() to print() how many people scored 85.

Python Editor

Run code to see output

In this article, we covered creating and accessing lists, slicing, adding and removing items, and sorting and searching.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Given nums = [10, 20, 30], what will nums contain after you run nums.append([40, 50])?

Q2Given items = [3, 1, 4, 1, 5], what does print(items.sort()) output?

Q3Given data = [10, 20, 30, 40], what's the result of data[-2:]?