What you will learn
- Define and identify: index, slice, append, pop, remove
- Slice a list
- Add and remove elements from a list
Reading
Do Now
Part 1 - Open up the console
Type the following example code using interactive mode
Example 1
>>> a = [123, 'First Item', 456, 'Second Item']
>>> b = a[0:2]
>>> print(a)
>>> print(b)
In your notebook
Respond to the following
- What happens to a?
- What is b?
- What type is b?
Example 2
>>> a = [123, 'First Item', 456]
>>> a.remove('First Item')
>>> print(a)
Continue in your notebook
Respond to the following questions
- What does
removedo? - What would the length of this list be after
remove?
Example 3
>>> a = [123, 'First Item', 456]
>>> a.pop()
>>> print(a)
Continue your responses in your notebook
- what does
popdo? - What is the difference between
removeandpop?
Example 4
>>> a = [123, 'First Item', 456, 'Second Item']
>>> b = a + ['Third Item']
>>> print(a)
>>> print(b)
Continue your responses to the following in your notebook
- What happens to a?
- What is b?
- What type is b?
Example 5
>>> a = []
>>> print(len(a))
>>> a.append('First Item')
>>> print(a)
In your Notebook
- What was the length of
[]? - What does
appenddo? What would the length be afterappend?
Lab
In your Notebook
1. Predict what will be printed. Then run the program and confirm
Example 1
a = ['a', 'b', 'c', 'd', 'e']
print(a[0:3])
print(a[1:4])
Example 2
a = ['a', 'b', 'c', 'd', 'e']
print(a[1:len(a) - 3])
Example 3
a = ['a', 'b', 'c', 'd', 'e']
b = a.remove('b')
print(a)
print(b)
Example 4
a = ['a', 'b', 'c', 'd', 'e']
a[0] = 'haha'
b = a.pop()
print(a)
print(b)
Example 5
a = ['a', 'b', 'c', 'd', 'e']
b = a + ['abc']
print(a)
print(b)
Example 6
a = ['a', 'b', 'c', 'd', 'e']
b = a.append('f')
print(a)
print(b)
2. In your Console
We are going to start implementing Tic-Tac-Toe using a single list.
-
The user picks a location on the board according to the number:
- Depending on the position that the user inputs, update the position of the board to an “X” to reflect that.
- Print the updated board out, but don’t worry about making it look pretty.
- Only need to implement one turn of the game
Check your understanding
Pick an answer for each question. You can try again until you get it right.
1. If nums = [10, 20, 30, 40, 50], what is nums[1:3]?
[10, 20, 30][20, 30, 40][30, 40][20, 30]
A slice starts at the first index and stops just before the second index.
2. After nums = [1, 2] and nums.append(3), what is nums?
[3, 1, 2][1, 2, 3][1, 2][4, 3]
The append method adds the item to the end of the list.
3. What is the difference between remove and pop?
removedeletes a given value, whilepoptakes off an item by position (the last one by default)removeadds an item andpopdeletes one- They are exactly the same
popworks only on strings
You tell remove which value to delete, while pop removes by index and defaults to the last item.