SyntaxPilot
Courses/Python/Lesson 10

Python · Lesson 10 of 40 · 11 min

Lists

queued

These are the notes for Python episode 10. Until now, every variable held one value. Today Raju wants to keep a whole week of chai sales, and seven separate variables fall apart, so we invent the list. You will learn how to create a list, why indexes start at 0, negative indexes, len(), looping over a list with sum(), max(), min() and an average, changing a list with append, insert, remove, pop and index assignment, slicing and in, the difference between sort() and sorted(), and the copy trap where = doesn't copy at all. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: seven variables for seven days

In episode 7 a loop added up Raju's sales and kept only the total. Now he asks better questions: which was my best day, my second best, did weekends sell more? For that we must keep every day's number. The obvious way is one variable per day:

day1 = 420
day2 = 380
day3 = 510
day4 = 290
day5 = 600
day6 = 750
day7 = 680

for i in range(1, 8):
    print(dayi)

Output:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print(dayi)
          ^^^^
NameError: name 'dayi' is not defined. Did you mean: 'day1'?

Why it failed: dayi is just another name that happens to contain the letter i. Python never glues the word day to the value of i. A variable name is a fixed label, so you can't count through names with a loop. With separate variables, every day needs its own line written by hand, finding the best day takes seven comparisons, and a year would need 365 variables.

The list: one name, many numbered values

On a train In Python
The whole train has one name: Rajdhani Express the list has one variable name: sales
Many coaches, one after another, each carrying people many items, in order, each holding one value
Every coach has a number, so you walk straight to it every item has an index, so sales[2] goes straight to it

A list is an ordered collection of values stored under one name. You write it with square brackets and commas:

sales = [420, 380, 510, 290, 600, 750, 680]
print(sales)
print(sales[0])
print(sales[6])
print(sales[-1])
print(len(sales))

Output:

[420, 380, 510, 290, 600, 750, 680]
420
680
680
7
  • An index is an item's position number. The first item is at index 0, not 1.
  • Seven items means indexes 0 to 6: the last index is always len(list) - 1.
  • Negative indexes count from the end: sales[-1] is the last item, sales[-2] the one before it (exactly like strings in episode 5).
  • len() gives the number of items.
sales = [420, 380, 510, 290, 600, 750, 680]
index:    0    1    2    3    4    5    6
negative:-7   -6   -5   -4   -3   -2   -1

A list can mix types, though usually it holds one kind of thing:

mix = ["Raju", 42, 3.5, True]
print(mix)
print(type(mix))

Output:

['Raju', 42, 3.5, True]
<class 'list'>

IndexError

sales = [420, 380, 510, 290, 600, 750, 680]
print(sales[7])

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(sales[7])
          ~~~~~^^^
IndexError: list index out of range

There is no coach number 7. The last index of a 7-item list is 6 (or -1).

Looping over a list, sum, max, min, average

The for loop from episode 8 walks through a list one item at a time, and Python has built-in helpers for the common questions:

sales = [420, 380, 510, 290, 600, 750, 680]
for s in sales:
    print(s, "*" * (s // 100))

print("Total:", sum(sales))
print("Best:", max(sales), "Worst:", min(sales))
print("Average:", sum(sales) / len(sales))

Output:

420 ****
380 ***
510 *****
290 **
600 ******
750 *******
680 ******
Total: 3630
Best: 750 Worst: 290
Average: 518.5714285714286

With seven variables, the best day took seven comparisons. With a list it's max(sales), and it works the same for 7 days or 365.

Function What it gives Example
len(x) number of items len(sales) → 7
sum(x) total of the numbers sum(sales) → 3630
max(x) / min(x) biggest / smallest max(sales) → 750
sum(x) / len(x) the average 518.57...

Changing a list: append, insert, remove, pop

Real data changes: a new day's sale arrives, a typo needs fixing, a wrong entry must go.

sales = [420, 380, 510]
sales.append(600)
print(sales)
sales.insert(0, 999)
print(sales)
sales[0] = 400
print(sales)
sales.remove(510)
print(sales)
last = sales.pop()
print(last, sales)

Output:

[420, 380, 510, 600]
[999, 420, 380, 510, 600]
[400, 420, 380, 510, 600]
[400, 420, 380, 600]
600 [400, 420, 380]
Code What it does
sales.append(600) adds 600 at the end
sales.insert(0, 999) puts 999 at index 0; everything else shifts right
sales[0] = 400 replaces the item at index 0
sales.remove(510) deletes the first item equal to 510
sales.pop() removes the last item and returns it (pop(i) removes index i)
sales.extend([1, 2]) adds every item of another list at the end

A function that belongs to a type and is called with a dot, like sales.append(...), is a method.

Mutable vs immutable

Something that can be changed after it's made is mutable. Lists are mutable. Strings are immutable:

name = "raju"
name[0] = "R"

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    name[0] = "R"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

To "change" a string you build a new one: name = name.capitalize().

Removing a missing value

sales = [420, 380, 510]
sales.remove(999)

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    sales.remove(999)
    ~~~~~~~~~~~~^^^^^
ValueError: list.remove(x): x not in list

Check first: if 999 in sales: sales.remove(999).

append vs extend

nums = [3, 1, 2]
nums.append([4, 5])
print(nums)
print(len(nums))

Output:

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

append adds its argument as one item (here, a whole list). To add each item, use extend:

marks = []
marks.append(85)
marks.append(92)
marks.extend([78, 64])
print(marks, len(marks))

Output:

[85, 92, 78, 64] 4

Slicing and in

Slicing works just like strings: list[start:stop], and the stop index is not included.

sales = [420, 380, 510, 290, 600, 750, 680]
print(sales[0:5])
print(sales[5:])
print(750 in sales)
print(100 in sales)

Output:

[420, 380, 510, 290, 600]
[750, 680]
True
False

x in list answers "is this value somewhere in the list?" with True or False. A slice always gives a new list.

sort() vs sorted()

To find the second best day, sort and take the second item. The trap:

sales = [420, 380, 510, 290, 600, 750, 680]
x = sales.sort()
print(x)
print(sales)

Output:

None
[290, 380, 420, 510, 600, 680, 750]

sales.sort() sorts the list in place and returns nothing, which Python calls None. So x is None, and the original Monday-to-Sunday order is gone. sorted() makes a new sorted list and leaves the original alone:

sales = [420, 380, 510, 290, 600, 750, 680]
top = sorted(sales, reverse=True)
print(top)
print("Second best:", top[1])
print(sales)

Output:

[750, 680, 600, 510, 420, 380, 290]
Second best: 680
[420, 380, 510, 290, 600, 750, 680]
list.sort() sorted(list)
Changes the original? yes, in place no
Returns None a new sorted list
Biggest first sales.sort(reverse=True) sorted(sales, reverse=True)
Use when you don't need the old order you need to keep the old order

The copy trap: = shares, .copy() copies

In real life In Python
Sharing a document link: both of you edit the same document backup = sales: two names for one list
A photocopy: scribble on yours, the original stays clean backup = sales.copy(): a separate list
sales = [420, 380, 510]
backup = sales
backup.append(0)
print("sales: ", sales)
print("backup:", backup)

Output:

sales:  [420, 380, 510, 0]
backup: [420, 380, 510, 0]

Both changed: = didn't copy anything, it gave the same list a second name. This is called aliasing. A real copy:

sales = [420, 380, 510]
backup = sales.copy()
backup.append(0)
print("sales: ", sales)
print("backup:", backup)

Output:

sales:  [420, 380, 510]
backup: [420, 380, 510, 0]

sales[:] (a slice of everything) and list(sales) also make a copy.

Common mistakes

Mistake What you see Why Fix
print(dayi) to loop over variables NameError: name 'dayi' is not defined. Did you mean: 'day1'? names can't be built from a counter use a list: sales[i]
sales[7] on a 7-item list IndexError: list index out of range indexes go 0 to len - 1 sales[6] or sales[-1]
sales.remove(999) ValueError: list.remove(x): x not in list the value isn't there if 999 in sales: first
name[0] = "R" on a string TypeError: 'str' object does not support item assignment strings are immutable build a new string
x = sales.sort() no error, x is None sort() works in place x = sorted(sales)
backup = sales no error, both lists change = shares the list backup = sales.copy()
nums.append([4, 5]) no error, a list inside the list append adds one item nums.extend([4, 5])

Mini project: Raju's weekly report

Two lists in the same order: day names and sales. Print a bar per day (one # for every ₹50), then the best day's name and the average.

# Mini project: Raju's weekly report
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
sales = [420, 380, 510, 290, 600, 750, 680]

for i in range(len(days)):
    print(days[i], "#" * (sales[i] // 50), sales[i])

best = sales.index(max(sales))
print("Best day:", days[best])
print("Average:", round(sum(sales) / len(sales)))

Output:

Mon ######## 420
Tue ####### 380
Wed ########## 510
Thu ##### 290
Fri ############ 600
Sat ############### 750
Sun ############# 680
Best day: Sat
Average: 519

range(len(days)) gives the indexes 0 to 6, so days[i] and sales[i] are the same day. sales.index(x) returns the position of the first item equal to x.

Extend it: add the worst day's name, and the weekend total using a slice.

Solution
worst = sales.index(min(sales))
print("Worst day:", days[worst])
print("Weekend total:", sum(sales[5:]))

Output:

Worst day: Thu
Weekend total: 1430

Practice

1. Store 5 marks in a list and print the highest, the lowest, the average, and every mark above the average.

Solution
marks = [72, 88, 95, 61, 79]
avg = sum(marks) / len(marks)
print("Highest:", max(marks))
print("Lowest:", min(marks))
print("Average:", avg)
for m in marks:
    if m > avg:
        print("Above average:", m)

Output:

Highest: 95
Lowest: 61
Average: 79.0
Above average: 88
Above average: 95

2. Remove the lowest mark from the list and print what's left.

Solution
marks = [72, 88, 95, 61, 79]
marks.remove(min(marks))
print(marks)

Output:

[72, 88, 95, 79]

3. Build a list of the even numbers from [3, 8, 1, 6] using a loop and append.

Solution
nums = [3, 8, 1, 6]
evens = []
for n in nums:
    if n % 2 == 0:
        evens.append(n)
print(evens)

Output:

[8, 6]

4. Reverse a list two ways.

Solution
nums = [1, 2, 3, 4, 5]
print(nums[::-1])
nums.reverse()
print(nums)

Output:

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

nums[::-1] is a new reversed list (a slice with step -1); nums.reverse() reverses in place and, like sort(), returns None.

5. A to-do list: add "Buy milk" and "Pay bill", put "Call Raju" first, then mark the item at index 1 as done with pop(1).

Solution
todo = []
todo.append("Buy milk")
todo.append("Pay bill")
todo.insert(0, "Call Raju")
done = todo.pop(1)
print("Done:", done)
print("Left:", todo)

Output:

Done: Buy milk
Left: ['Call Raju', 'Pay bill']

Quick quiz

a = [1, 2, 3]
b = a
b[0] = 99
print(a[0])

What does it print? 1, 99, IndexError, or [99, 2, 3]?

Answer

99. b = a doesn't copy: a and b are two names for the same list, so changing it through b changes what a sees.

Interview questions

  1. Why do Python lists start at index 0? The index is the offset from the start: the first item is 0 steps from the beginning.
  2. What's the difference between sort() and sorted()? sort() is a list method that sorts in place and returns None; sorted() works on any iterable and returns a new list.
  3. Is a list mutable? Is a string? A list is mutable (items can be changed, added, removed); a string is immutable.
  4. How do you copy a list? Why doesn't b = a work? a.copy(), a[:] or list(a). b = a only makes a second name for the same list.
  5. append vs extend? append(x) adds x as one item; extend(iterable) adds each item of the iterable.
  6. How do you get the second largest value? sorted(set(nums), reverse=True)[1] (the set removes duplicates; sets are next episode). For [4, 9, 2, 9, 7] this gives 7.
  7. What does sales[-1] return for an empty list? IndexError: list index out of range: an empty list has no last item.

Glossary

Term Meaning Example
List An ordered collection of values under one name, in square brackets [420, 380, 510]
Item (element) One value inside a list 380
Index An item's position number, starting at 0 sales[0] is the first
Negative index Position counted from the end sales[-1] is the last
len() Number of items len(sales) → 7
IndexError Asking for a position that doesn't exist sales[7] on 7 items
sum() / max() / min() Total, biggest, smallest of a list of numbers max(sales) → 750
Method A function that belongs to a type, called with a dot sales.append(600)
append / insert Add at the end / at a position sales.insert(0, 999)
remove / pop Delete by value / take out by position (last by default) sales.pop()
Mutable Can be changed after it's made lists
Immutable Can't be changed after it's made strings, numbers
ValueError Right type, wrong value, e.g. removing a value that isn't there sales.remove(999)
Slice A part of a list, [start:stop], stop not included sales[0:5]
in True if the value is in the list 750 in sales
None Python's "nothing" value what sort() returns
In place Changes the original object instead of making a new one sales.sort()
sorted() Returns a new sorted list sorted(sales, reverse=True)
Alias A second name for the same object backup = sales
.copy() Makes a separate list with the same items backup = sales.copy()
.index(x) Position of the first item equal to x sales.index(750) → 5

Summary

  • A list keeps many values under one name, in order: sales = [420, 380, 510].
  • Indexes start at 0; the last index is len - 1; [-1] is the last item. A wrong index is an IndexError.
  • for s in sales: walks through the list; sum, max, min and len answer the common questions.
  • Lists are mutable: append, insert, list[i] = x, remove (a missing value is a ValueError), pop.
  • Slices [a:b] and x in list work like strings.
  • sort() changes the list and returns None; sorted() returns a new list.
  • = shares a list; .copy() copies it.

Next episode: tuples and sets. Data that must never change, like a GPS location, and a guest list where nobody appears twice.