Lists
Lists store ordered, changeable collections of items.
Syntax
fruits = ['apple', 'banana']A list is an ordered, changeable collection. Write it with square brackets, separating items with commas.
Key points
- Items are accessed by index, starting at
0. len(list)gives the number of items.- Lists can hold mixed types and can grow or shrink.
Common methods: append() adds to the end, pop() removes from the end, insert() adds at a position, and remove() deletes a value.
Example
fruits = ['apple', 'banana', 'cherry']
print(fruits[0])
print(len(fruits))
fruits.append('date')
print(fruits)
fruits[1] = 'blueberry'
print(fruits)
# Output:
# apple
# 3
# ['apple', 'banana', 'cherry', 'date']
# ['apple', 'blueberry', 'cherry', 'date']When to use it
- A to-do app stores task strings in a list and appends or removes items as the user acts.
- A web scraper collects all product prices into a list and then sorts them to find the cheapest.
- A playlist manager keeps song titles in a list and pops the first item when the current track ends.
More examples
Create and modify a list
Creates a list then uses append() to add an item and remove() to delete one by value.
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.remove('banana')
print(fruits)
# Output:
# ['apple', 'cherry', 'date']Indexing and slicing
Accesses list elements by positive and negative index and extracts a sub-list with slicing.
nums = [10, 20, 30, 40, 50]
print(nums[0]) # 10
print(nums[-1]) # 50
print(nums[1:4]) # [20, 30, 40]Sort, reverse, and length
Sorts a list in place, reverses it, and checks its length with len().
scores = [88, 42, 95, 73, 61]
scores.sort()
print(scores) # [42, 61, 73, 88, 95]
scores.reverse()
print(scores[0]) # 95 (highest after reverse)
print(len(scores)) # 5
Discussion