List tools
Handy list tools:
nums = [5, 2, 9] nums.sort() # sorts in place -> [2, 5, 9] nums.insert(0, 1) # put 1 at index 0 nums.remove(5) # remove the first 5 last = nums.pop() # remove & return the last item 9 in nums # membership test -> bool sum(nums) # total of the numbers min(nums), max(nums) # smallest and largest ordered = sorted(nums) # new sorted list; nums is unchanged nums.count(2) # number of occurrences of 2 ordered[:2] # first two items; list slices work like string slices
A for loop goes straight through the items: for n in nums:
See it run
nums = [4, 1, 3] ordered = nums.sort() print(ordered) print(nums)
sort() changes the list itself. Watch what it hands back.
Practice list tools
Exercise 1
With scores = [72, 95, 88, 61]:
- sort
scoresin place (ascending) best= the highest scoreaverage= the mean, usingsumandlen(79.0)
Exercise 2
Use the week's temps in the editor below.
- The 30 was a glitch: remove it by value.
- A late reading of 22 belongs at the start: insert it at index 0.
- Then set
hottest,coldestandspread(hottest minus coldest).
Exercise 3
Use the race times in the editor below, measured in seconds (lower is faster). Without changing times:
podium= a new list of the three fastest times, fastest firstties= how many runners share the fastest time (use.count)in_time=Trueif60.3is in the list (usein)
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Loading exercise content…
Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.
Memory · names → values
Variables appear here as Python creates them.
Output & plots