PyComplete Python Course
Beginner 50 min

Module 06 — Lists

Python's flexible, ordered, changeable collection — the workhorse data structure.

Prerequisite: Module 05 — Functions

After this lesson, you will be able to

  • Create, index, and slice lists
  • Add and remove items with append(), insert(), remove(), pop()
  • Loop through a list, including nested lists
  • Convert between lists and strings with join() and split()

Concept & Syntax

A list is an ordered, changeable collection of values, written with square brackets: [10, 20, 30]. Lists can hold any type — even a mix of types, or other lists — and they're the tool you reach for whenever you need to keep track of "more than one" of something: a shopping list, student names, scores in a game.

Unlike a string, a list is mutable — you can change, add, or remove items after it's created. That single property (mutability) is what separates lists from the tuples you'll meet in the next module.

Syntax
numbers = [10, 20, 30, 40]
numbers.append(50)
numbers[0]      # first item
numbers[-1]     # last item
numbers[1:3]    # a slice

Examples

Creating and indexing a list Very Easy

Creating and indexing a list
scores = [88, 92, 79, 95]
print(scores[0])
print(scores[-1])
Output88 95

Lists use the same 0-based indexing as strings — scores[0] is the first score, scores[-1] is the last.

append(), insert(), remove() Easy

append(), insert(), remove()
tasks = ["email", "meeting"]
tasks.append("lunch")
tasks.insert(1, "review PR")
tasks.remove("meeting")
print(tasks)
Output['email', 'review PR', 'lunch']

append() adds to the end; insert(index, value) adds at a specific position; remove(value) deletes the first matching item.

Looping through a list Easy

Looping through a list
colors = ["red", "green", "blue"]
for color in colors:
    print(color.upper())
OutputRED GREEN BLUE

A for loop gives you each item in turn — no manual indexing needed.

Nested lists Intermediate

Nested lists
grid = [[1, 2], [3, 4], [5, 6]]
print(grid[1][0])
for row in grid:
    print(row)
Output3 [1, 2] [3, 4] [5, 6]

A list can contain other lists. grid[1][0] means 'row at index 1, then item at index 0 in that row'.

join(), split(), min(), max() Real World

join(), split(), min(), max()
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print("-".join(words))
scores = [88, 92, 79, 95]
print(min(scores), max(scores))
Output['the', 'quick', 'brown', 'fox'] the-quick-brown-fox 79 95

split() turns a string into a list of words; join() does the reverse, gluing a list back into a string with a separator.

Visual Explanation

numbers = [10, 20, 30, 40]100201302403
Every item in a list sits at a numbered index, starting from 0.
🔍 What happens internally? (advanced)

Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.

Watch a list grow

Use the controls below to run this example one line at a time and watch the interpreter's memory update live.

Code

Code
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)

Interpreter state

Console output

Common Mistakes

✗ Common mistake 1

Accessing an index that doesn't exist raises an error rather than returning something like None.

✗ Avoid this
This raises IndexError: list index out of range
colors = ["red", "green"]
print(colors[5])
✓ Better approach
Fixed
colors = ["red", "green"]
if len(colors) > 5:
    print(colors[5])
else:
    print("No item at that index")
✗ Common mistake 2

A Python list is not a fixed-size array like in some other languages — but pop() and remove() still fail loudly on invalid input, so check first.

✗ Avoid this
This raises ValueError: list.remove(x): x not in list
items = [1, 2, 3]
items.remove(9)
✓ Better approach
Fixed
items = [1, 2, 3]
if 9 in items:
    items.remove(9)
✓ Best practices
  • Use in to check membership before removing: if x in my_list:.
  • Prefer list comprehensions (next module) over manual append loops when building a new list.
  • Name list variables in the plural: students, not student.
  • Use len(my_list) rather than hardcoding a list's size.

Exercise & Challenge

Exercise 1 — Predict the output

Given this code
nums = [5, 1, 4, 2, 3]
nums.sort()
print(nums)

What does this print?

🏆 Challenge

Write a program that starts with an empty list, adds five numbers typed by the user (converted with int()), and then prints the list along with its sum and average.

  • Use a loop to collect 5 numbers with input()
  • Use append() to build the list
  • Print the sum and the average (sum / count)
💡 Need a hint?

sum(my_list) adds all the numbers in a list for you.

🔍 Show a sample solution
Python
numbers = []
for i in range(5):
    numbers.append(int(input("Enter a number: ")))
print(numbers)
print("Sum:", sum(numbers))
print("Average:", sum(numbers) / len(numbers))

Quiz

Answer every question, then submit to see your score and explanations.

1. Which method adds an item to the end of a list?

insert()
append()
add()
extend()
append() adds a single item to the end of the list.

2. What is the key difference between a list and a tuple?

Lists can't hold numbers
Lists are mutable (changeable); tuples are not
Tuples are always faster to create
There is no difference
Mutability is the core distinction — you'll see it in the next module.

3. What does grid[1][0] mean for grid = [[1,2],[3,4]]?

Item 1 of the whole grid
Row 1, item 0 → 3
Row 0, item 1 → 2
This is invalid syntax
grid[1] is [3, 4], and [0] of that is 3.

4. Which function turns a list of words back into a single string?

split()
join()
combine()
merge()
'-'.join(list_of_words) glues the words together using the separator.

5. What happens if you access an index beyond a list's length?

Python returns None
Python returns 0
IndexError is raised
The list grows automatically
Out-of-range indexing raises an IndexError.

Summary

  • Lists are ordered, mutable collections written with square brackets.
  • append(), insert(), remove(), and pop() modify a list in place.
  • Lists can be nested; access an inner item with grid[row][col].
  • split() and join() convert between strings and lists of words.

Related lessons

Saved privately in your browser — no account needed.