Data StructuresBeginner9 min22 / 63

Lists

Learn how to store and manage collections of things in Python using lists — one of the most useful tools in any programmer's toolkit.

Imagine you're writing a grocery list on paper. You jot down items one after another, you can add more at the bottom, cross things out, or reorder them. Python's list works exactly the same way — it's an ordered collection of items you can change whenever you like.

Lists are everywhere in real programs: a playlist of songs, a queue of tasks, a table of scores. Once you understand lists, a huge range of programming problems become easy to solve.

See it in action

Visual walkthrough1 / 6
1

Your First Collection of Things

A Python list is an ordered collection of items you can change anytime. Think of it like a grocery list — you can add, remove, and reorder items whenever you like.

Lists are one of the most useful tools in all of Python — you'll use them constantly.

#Creating a List

You create a list with square brackets [], separating items with commas. Lists can hold any type of value — numbers, strings, booleans, even other lists — and they can mix types freely.

Lists can hold any types, even mixed together
fruits = ["apple", "banana", "cherry"]
scores = [98, 72, 85, 60]
mixed = ["hello", 42, True, 3.14]
empty = []

print(fruits)
print(mixed)

#Indexing and Slicing

Each item in a list has a position number called an index. Python starts counting from 0, not 1. So the first item is at index 0, the second at 1, and so on.

You can also count from the end using negative indexes: -1 is the last item, -2 is second-to-last, etc.

Slicing lets you grab a range of items using list[start:stop] — it returns everything from start up to (but not including) stop.

Indexing picks one item; slicing picks a range
fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0])    # first item
print(fruits[2])    # third item
print(fruits[-1])   # last item
print(fruits[1:3])  # slice: items at index 1 and 2
Common mistake

Index 0, not 1!

A very common beginner mistake is reaching for index 1 when you want the first item. Remember: Python lists start at 0. If you try fruits[4] on a 4-item list, Python throws an IndexError — there is no index 4 when the last index is 3.

#Changing Items

Lists are mutable — that's a fancy word for "changeable". You can replace any item by assigning to its index directly.

Assigning to an index changes that item in place
colors = ["red", "green", "blue"]
print(colors)

colors[1] = "yellow"   # replace "green" with "yellow"
print(colors)

#Useful List Methods

Python lists come with built-in methods — actions you can call on a list using dot notation (my_list.method()). Here are the most important ones:

  • append(item) — add one item to the end
  • insert(index, item) — add an item at a specific position
  • remove(item) — remove the first occurrence of a value
  • pop(index) — remove and return the item at a position (default: last)
  • extend(other_list) — add all items from another list to the end
  • sort() — sort the list in place (modifies the original)
  • reverse() — reverse the order in place
  • count(item) — count how many times a value appears
  • index(item) — find the position of the first occurrence of a value
Common list methods in action
nums = [3, 1, 4, 1, 5]

nums.append(9)
print("append:", nums)

nums.insert(2, 99)
print("insert at 2:", nums)

nums.remove(1)        # removes first 1
print("remove first 1:", nums)

popped = nums.pop()   # removes last item
print("popped:", popped, "| list now:", nums)

print("count of 1:", nums.count(1))
sort(), reverse(), and extend() all modify the list in place
letters = ["c", "a", "b"]
letters.sort()
print("sorted in place:", letters)

letters.reverse()
print("reversed:", letters)

more = ["d", "e"]
letters.extend(more)
print("extended:", letters)

#len() and the in Operator

Two quick but essential tools:

  • len(my_list) tells you how many items are in the list.
  • item in my_list checks whether a value exists anywhere in the list — it gives back True or False.
len() counts items; 'in' checks membership
animals = ["cat", "dog", "rabbit"]

print(len(animals))
print("dog" in animals)
print("fish" in animals)

#Looping Through a List

One of the most common things you'll do with a list is visit each item one by one. Python's for loop makes this effortless.

for loops let you process every item in a list
tasks = ["wash dishes", "buy milk", "call mom"]

for task in tasks:
    print("TODO:", task)

#sorted() vs .sort()

Tip

sorted() returns a new list; .sort() changes the original

Use sorted(my_list) when you want a new sorted list and need to keep the original untouched. Use my_list.sort() when you want to sort in place and don't need the original order anymore. This small distinction prevents tricky bugs.

sorted() vs .sort() — know which one you need
scores = [5, 2, 8, 1]

new_order = sorted(scores)   # original unchanged
print("original:", scores)
print("sorted copy:", new_order)

scores.sort()                # modifies in place
print("after .sort():", scores)

#Nested Lists

A list can contain other lists as items. This is called a nested list and is useful for representing things like a grid, a table of data, or a matrix. You access inner items by chaining indexes.

Nested lists — index twice to reach an inner item
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(grid[0])       # first row
print(grid[1][2])    # row 1, column 2

#The Copy Gotcha

Watch out

Assigning a list does NOT copy it

When you write b = a, both a and b point to the same list in memory. Changing b also changes a! This is called aliasing and surprises almost every beginner at least once.

To make a true independent copy, use b = a.copy() or b = a[:].

Use .copy() to avoid accidentally sharing a list
a = [1, 2, 3]
b = a          # b is NOT a copy — it's the same list!
b.append(99)
print("a:", a)  # a is also changed!

c = a.copy()   # real copy
c.append(42)
print("a after copy change:", a)  # a is safe now
Think of it like

Lists are like a whiteboard

Think of a list as a shared whiteboard. If two people have the same whiteboard, when one person erases something, it's gone for both. .copy() is like taking a photo of the whiteboard — changes to the photo don't affect the original.

Quick check

What does this code print? ```python items = ["a", "b", "c", "d"] print(items[-2]) ```

Key takeaways

  • Lists store ordered, changeable collections of any values — even mixed types.
  • Indexing starts at 0; use negative indexes to count from the end.
  • Methods like append, remove, sort, and pop let you modify lists in place.
  • Use sorted() for a new sorted copy; use .sort() to sort the original.
  • Assigning one list to another variable does NOT copy it — use .copy() to get an independent list.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1])
print(fruits[-1])
Fix the bug#2

This code has a bug. What is wrong?

fix-bug
animals = ["cat", "dog", "rabbit"]
print(animals[3])
Fill in the blank#3

Complete the code so it adds "mango" to the end of the list, then prints how many items are in the list.

fruits = ["apple", "banana"]
fruits.("mango")
print((fruits))
Reorder the lines#4

Put these lines in the right order to create a list, sort it, and print the sorted result.

1
scores = [3, 1, 4, 1, 5]
2
print(scores)
3
scores.sort()
Your turn
Practice exercise

Create a list called wishlist with at least 3 items (strings of things you'd like). Then: (1) print the first and last items using indexing, (2) add a new item with append(), (3) sort the list alphabetically and print it, (4) print how many items are in the list using len().

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable