Lesson 1 · Unit 04
Lists
Indexes, slices, changing a list, sharing one
What you practise
- Indexes from 0 and from the end, slices,
append,pop,insert,len,in, looping over a list, a list can change and two names can share it
Try a question from this lesson
Pick one
A list holds several values in order. The number in square brackets picks one out, and the counting starts at 0. What does this show?
scores = [70, 85, 90]
print(scores[1])Correct answer
85
Why
Positions are counted from 0, so scores[0] is 70 and scores[1] is the second value, 85. Counting from 0 feels odd for about a week and then becomes natural.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Lists and indexes
A list is written in square brackets with commas between the values. The values are called items.
Each item has a position called its index, counted from 0. A negative index counts back from the end: -1 is the last item.
len(...) gives the number of items.
names = ["Ada", "Bo", "Cy"]
print(names[0]) # Ada
print(names[-1]) # Cy
print(len(names)) # 3Concept
Changing a list
A list can change after it is made. The tools for that are methods: functions that belong to a value and are called with a dot.
append adds an item at the end. insert adds one at an index. pop removes the last item and hands it back. Giving a value to an index replaces that item.
todo = ["wash", "cook"]
todo.append("shop") # add at the end
todo.insert(0, "wake") # add at index 0
last = todo.pop() # remove the last
todo[0] = "rest" # replace
print(todo, last)
# ['rest', 'wash', 'cook'] shopConcept
Slices
A slice copies part of a list into a new list. nums[start:stop] runs from index start up to, but not including, index stop: the same rule as range.
Leave out the start to begin at the beginning. Leave out the stop to go to the end.
nums = [10, 20, 30, 40, 50]
print(nums[1:3]) # [20, 30]
print(nums[:2]) # [10, 20]
print(nums[3:]) # [40, 50]9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.