Lists, dictionaries, strings
Lists
Goal: Create, index, modify and loop over lists · 10 min
A list stores several values in order: nums = [4, 8, 15].
- Indexing starts at 0:
nums[0]is 4; negative indices count from the end:nums[-1]is 15. len(nums)gives the length.- Lists are mutable:
nums[1] = 9,nums.append(16),nums.remove(4),nums.pop(). - Useful built-ins:
sum,min,max,sorted; membership:8 in nums. - Slicing:
nums[1:3]takes indices 1 and 2.
Worked example: Average grade
- Store the grades in a list.
- sum(...) / len(...) gives the mean.
- round(..., 2) rounds for display.
grades = [2, 1, 3, 2, 4]
print(round(sum(grades) / len(grades), 2))Output:
2.4