Free visual Python lesson

Python Lists — Explained Visually

A list is an ordered row of boxes you can change. Press Play and watch items get added and removed.

Python code

1nums = [4, 8, 15]
2nums.append(16)
3nums[0] = 5
4nums.remove(8)
5print(nums)

Variables / Memory

Memory is empty.

Execution

STEP 1 / 6Step 1 of 6. Program starts.

Program starts.

Output

Flow chart

RanNowTrueFalseChecked, not taken◇ decision · ▱ input/output
StartStartnums = [4, 8, 15]nums = [4, 8, 15]nums.append(16)nums.append(16)nums[0] = 5nums[0] = 5nums.remove(8)nums.remove(8)print(nums)print(nums)EndEnd

Creating and reading a list

fruits = ["apple", "mango", "kiwi"]
print(fruits[0])   # apple
print(fruits[-1])  # kiwi
print(len(fruits)) # 3

Positions start at 0. A negative index counts from the end.

Changing a list

  • fruits.append("grape") adds to the end.
  • fruits.remove("mango") removes the first match.
  • fruits[1] = "banana" replaces an item.

Looping over a list

nums = [4, 7, 2]
total = 0
for x in nums:
    total = total + x
print(total)  # 13

Common beginner mistakes

  • Using fruits[3] on a 3-item list — the last index is 2.
  • Writing fruits = fruits.append(x), which sets the list to None.

Practice exercises

Try each one yourself first, then open it in the Visualizer to watch every line run.

Exercise 1

Shopping list

Start with an empty list, add three items, remove one, and print the list and its length.

items = []
# append, append, append, remove
Hint

Use items.append("milk") and items.remove("milk").

Show solution and explanation
items = []
items.append("milk")
items.append("bread")
items.append("eggs")
items.remove("bread")
print(items, len(items))

Watch the list grow box by box in memory, then shrink. remove deletes the first matching item and later items slide left.

Watch the solution step by step

Exercise 2

Average marks

Work out the average of a list of marks.

marks = [70, 85, 60, 90]
# total, then divide
Hint

Loop to add them up, then divide by len(marks).

Show solution and explanation
marks = [70, 85, 60, 90]
total = 0
for m in marks:
    total = total + m
print(total / len(marks))  # 76.25

total grows each round; dividing by the number of items gives the average. / always gives a decimal answer.

Watch the solution step by step

Exercise 3

Only the evens

Build a new list containing only the even numbers.

nums = [3, 8, 5, 12, 7, 4]
evens = []
# loop and append
Hint

Append x when x % 2 == 0.

Show solution and explanation
nums = [3, 8, 5, 12, 7, 4]
evens = []
for x in nums:
    if x % 2 == 0:
        evens.append(x)
print(evens)  # [8, 12, 4]

The original list is untouched; the new list only receives items that pass the test.

Watch the solution step by step

Try your own code

Paste any code into the free visualizer, or sign up free for all visual lessons with quizzes and progress tracking.