Storing many values: a whole inbox in one variable
Introduction to Data Science and Machine Learning · Md Mahbub E Noor · University of Barishal
inbox = ["Hi", "Win cash", "Class at 10"] print(inbox[1])
len() counts the itemsmsg1 = "Win a free phone" msg2 = "Class moved to 305" msg3 = "Claim your prize" inbox = [msg1, msg2, msg3] print(inbox) print(len(inbox))
['Win a free phone', 'Class moved to 305', 'Claim your prize'] 3
scores = [72, 85, 90]
print(scores)
[72, 85, 90]
[ opens the list] closes the list"Win cash""Class 305""Claim prize""See you"inbox = ["Win cash", "Class 305",
"Claim prize", "See you"]
print(inbox[0])
print(inbox[2])
print(inbox[-1])
print(inbox[-2])Win cash Claim prize See you Claim prize
inbox[1:3]
"Win cash""Class 305""Claim prize""See you"print(inbox[1:3]) print(inbox[:2]) print(inbox[2:])
['Class 305', 'Claim prize'] ['Win cash', 'Class 305'] ['Claim prize', 'See you']
nums = [10, 20, 30, 40, 50] print(nums[1:4]) print(nums[-3:]) print(len(nums[2:]))
What will this print? Write your prediction as a comment before you run the cell.
nums = [10, 20, 30, 40, 50] print(nums[1:4]) print(nums[-3:]) print(len(nums[2:]))
[20, 30, 40] [30, 40, 50] 3
[1:4] takes positions 1, 2, 3: stop before 4[-3:] means the last three itemslen() works on itappend(x) adds to the endinsert(i, x) adds at position ilist[i] = x replaces an itemremove(x) deletes the first xpop() removes and returns the last itemtasks = ["read", "code"]
tasks.append("sleep")
tasks.insert(0, "eat")
tasks[1] = "study"
tasks.remove("code")
last = tasks.pop()
print(tasks)
print(last)['eat', 'study'] sleep
Each row runs one line. Follow how the list looks after it.
tasks = ["read", "code"]
tasks.append("sleep")
tasks.insert(0, "eat")
tasks[1] = "study"
tasks.remove("code")
last = tasks.pop()| step | operation | tasks after this line |
|---|---|---|
| 1 | create | ['read', 'code'] |
| 2 | append | ['read', 'code', 'sleep'] |
| 3 | insert | ['eat', 'read', 'code', 'sleep'] |
| 4 | replace [1] | ['eat', 'study', 'code', 'sleep'] |
| 5 | remove | ['eat', 'study', 'sleep'] |
| 6 | pop -> 'sleep' | ['eat', 'study'] |
Next row: arrow key or the ▶ button. Predict it first!
len, max, min, sum work on whole listsx in list checks membershipcount(x) and index(x) find itemssorted(list) gives a new sorted list; the original staysnums = [5, 3, 8, 3, 1] print(len(nums), max(nums), min(nums), sum(nums)) print(8 in nums) print(nums.count(3)) print(nums.index(8)) print(sorted(nums)) print(nums)
5 8 1 20 True 2 2 [1, 3, 3, 5, 8] [5, 3, 8, 3, 1]
nums = [5, 3, 8] result = nums.sort() print(nums) print(result)
What will this print? Write your prediction as a comment before you run the cell.
nums = [5, 3, 8] result = nums.sort() print(nums) print(result)
[3, 5, 8] None
.sort() sorts the list itself, in placeNonesorted(nums) returns a new sorted list insteadnums = nums.sort(): you lose the listlen() counts charactersword[0] = "J" gives an error (see the mistakes slide)word = "PYTHON" print(word[0], word[-1]) print(word[1:4]) print(len(word))
P N YTH 6
student = ("Nadia", 21, "CSE")
print(student[0])
print(len(student))
Nadia 3
student = ("Nadia", 21, "CSE")
print(student[1])
student[1] = 2221 TypeError: 'tuple' object does not support item assignment
name, age, dept = student gives each item a namea, b = b, a swaps two values in one linename, age, dept = student print(name) print(age) a, b = 1, 2 a, b = b, a print(a, b)
Nadia 21 2 1
b = a does not copy the lista.copy() for a real copya = [1, 2, 3] b = a b.append(4) print(a) c = a.copy() c.append(5) print(a) print(c)
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
WATCH FOR
Silent video: press play, pause any time.
Read the last line of an error first. It names the problem.
| What you typed | What Python says | What it means |
|---|---|---|
print(inbox[10]) | IndexError: list index out of range | No position 10. Valid positions: 0 to len(inbox) - 1. |
student[1] = 22 | TypeError: 'tuple' object does not support item assignment | Tuples cannot be changed. Use a list, or build a new tuple. |
nums.remove(99) | ValueError: list.remove(x): x not in list | 99 is not in the list. Check with 99 in nums first. |
word[0] = "J" | TypeError: 'str' object does not support item assignment | Strings cannot be changed. Build a new one: "J" + word[1:]. |
Work in pairs. 15 minutes. No loops yet: use indexing, slicing and list functions.
Use sorted() to print the second largest of [4, 9, 2, 7]. Expected: 7. Bonus: what goes wrong with [4, 9, 9, 2]?
Print the first two and the last two messages of a 6-message list, using slices.
Swap the first and last items of a list. Test: [1, 2, 3, 4] becomes [4, 2, 3, 1].
Store (name, roll, cgpa) as a tuple, unpack it, and print one f-string sentence.
Show these after students have tried the exercises.
The bonus shows a real limitation: with a repeated maximum, [-2] returns the maximum again.
nums = [4, 9, 2, 7] print(sorted(nums)[-2]) print(sorted([4, 9, 9, 2])[-2]) inbox = ["m1", "m2", "m3", "m4", "m5", "m6"] print(inbox[:2]) print(inbox[-2:])
7 9 ['m1', 'm2'] ['m5', 'm6']
Swapping uses tuple unpacking. Unpacking gives each field of a record its own name.
items = [1, 2, 3, 4]
items[0], items[-1] = items[-1], items[0]
print(items)
record = ("Nadia", 1042, 3.71)
name, roll, cgpa = record
print(f"{name} (roll {roll}) has CGPA {cgpa}")[4, 2, 3, 1] Nadia (roll 1042) has CGPA 3.71
In the lab you can
Opens in a new tab and works offline. All labs: labs/START_HERE.html
[a, b, c] | Make a list |
x[0], x[-1] | First item, last item |
x[1:3] | Items 1 and 2 (stop before 3) |
append / insert | Add items |
remove / pop | Delete items |
sorted(x) / x.sort() | New sorted list / sort in place |
(a, b, c) | Make a tuple (fixed) |
n, a, d = t | Unpack a tuple |
x.copy() | A real, separate copy |
Due before Lecture 3.3 · [date]
Predict first: x = [3, 1, 2]; print(x[::-1]); print(x[5:]); print(sorted(x) == x).
Make a list of 5 marks. Print the highest, lowest, average (sum / len) and the marks sorted.
Start with 3 messages. Add 2, replace the second, remove one by value, and print the list after each step.
Draw a trace table (step, list after) for the Inbox editor code by hand, then check it by printing.
In 2 sentences: why does b = a followed by b.append(4) change a?
Watch it again at home to revise.