List indexing and slicing
The indexing and slicing operations we saw with strings also work on lists.
List Index
From left to right, the index number starts from 0. From right to left (counting backwards), the index starts with -1.
Accessing an element: Like with strings, enclose the index number with square brackets to access a list item, like lst[i]
.
A list is mutable, which means you can change its contents even after you create it. We can assign new value to an element using list index:
lst[i] = new value
Example:
dates = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
# access to an element
print(dates[1]) # Tue
print(dates[0]) # Mon
# change the value of an element
dates[0] = 'First day'
print(dates[0]) # First day
# the last item
print(dates[6]) # Sun (the last item)
print(dates[-1]) # Sun (also the last item)
print(dates[len(dates)-1]) # Sun (the last item again)
print(len(dates)) # 7
In the previous example, dates[6], dates[-1]
, and dates[len(dates)-1]
all point to the same item -- the last element in the list.
Note: a string is immutable, and you cannot change its content once created.
Built-in function len()
Similar to string, the len()
function reports on the size of an list, or the number of elements in the list.
List Slice
Remember the range(start, end, step)
function? Start, end, and step can be used with lists too.
list[start:end:step]
gives you a slice, or piece, of a list.
start
indicates the index in the list where you want to begin your slice. If omitted, its default value is 0
, which means the slice starts from the beginning of the list.
end
is the index where your list ends. The slice you get will exclude the end index itself. If omitted, the slice goes until the end of the list.
step
is the number the index increases by. If omitted, its default value 1
.
# list slice
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print(numbers[8:]) # [9, 10, 11, 12]
print(numbers[:4]) # [1, 2, 3, 4]
print(numbers[1:6]) # [2, 3, 4, 5, 6]
print(numbers [::3]) # [1, 4, 7, 10] (every third number)
We can use the list index to reverse a list:
# reverse list
num = [0,1,2,3,4,5,6]
numR = num[::-1] # reverse a list, from end to start, going backward
print(numR) # [6, 5, 4, 3, 2, 1, 0]
num2 = num[4:1:-1]
print(num2) # [4, 3, 2] (a piece of backward list)