Lists
Basics8 min readLesson 5 of 8
A list is an ordered collection of values, written in square brackets with commas between items. The order matters because each item has a position. Lists can grow and shrink, so they suit a row of names or a set of scores. A list may hold values of different types, though a list of related values is easier to work with.
fruits = ['mango', 'pear', 'guava']
print(fruits[0])
print(fruits[-1])
print(len(fruits))Output
mango guava 3
5.1 Indexing and slicing
Indexes start at 0, so the first item is items[0]. A slice copies part of the list: items[1:3] contains positions 1 and 2, and stops before 3. Slicing returns a new list, while indexing returns the item stored at that position.
5.2 Changing the list in place
append()adds an item at the end.insert()adds an item at a chosen position.pop()removes an item and returns it.
tasks = ['read', 'write']
tasks.append('rest')
tasks[0] = 'review'
print(tasks)Output
['review', 'write', 'rest']
5.3 Common mistake
tasks = tasks.append('rest') looks like it updates the list, but it sets tasks to None. append() adds the item and returns None, so the assignment throws away the list name. Call append() on its own line, then continue using the same list name.
scores = [72, 85, 91, 64]
print(scores[1:3])
print(sum(scores))
print(max(scores))Output
[85, 91] 312 91
5.4 Practice
- Make a list of four tasks and add a fifth with
append(). - Replace the second task, then remove the last one with
pop(). - Print the final list and its length after each change, then try reading index
10and read the error message.
