4.1 Lists and Slicing
A list stores multiple values in order. Lists are created with square brackets [], and indexes start from 0.
Accessing list elements
Python supports forward indexes and negative indexes. -1 means the last element.
lst = [1, 2, 3]
print(lst[0]) # 1
print(lst[1]) # 2
print(lst[2]) # 3
print(lst[-1]) # 3
print(lst[-2]) # 2Accessing a position that does not exist, such as lst[3], raises an IndexError.
Concatenation and repetition
+ concatenates two lists. * repeats a list.
lst = [1, 2, 3] + [4, 5, 6]
print(lst) # [1, 2, 3, 4, 5, 6]
lst = [1, 2, 3] * 3
print(lst) # [1, 2, 3, 1, 2, 3, 1, 2, 3][1, 2, 3] + [4] creates a new list, while methods such as append() and insert() mutate the original list.
The in operator
in checks whether a value exists in a sequence. The result is a Boolean value.
languages = ["C", "C++", "Python", "Java"]
key = input("Enter a language: ")
if key in languages:
print("Found")
else:
print("Not found")One possible run:
Enter a language: Python
FoundSlicing
Slicing extracts part of a sequence:
lst[start:end:step]start: included.end: excluded.step: defaults to1.
lst = list(range(10))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(lst[2:7]) # [2, 3, 4, 5, 6]
print(lst[:5]) # [0, 1, 2, 3, 4]
print(lst[3:]) # [3, 4, 5, 6, 7, 8, 9]
print(lst[::2]) # [0, 2, 4, 6, 8]Two-dimensional lists
A two-dimensional list is a list of lists. It is often used for tables, boards, and matrices.
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
print(matrix[0][0]) # 1
print(matrix[1][2]) # 7matrix[1][2] means: take row 1, then take column 2 inside that row. Both indexes start from 0.
Matrix addition can be done with nested loops. The outer loop controls rows, and the inner loop controls columns.
Matrix addition and subtraction require two matrices with the same shape. If and are both matrices, then the result matrix is also . "Element by element" means row , column is only combined with row , column from the other matrix.
A = [
[1, 3],
[1, 0],
[1, 2]
]
B = [
[0, 0],
[7, 5],
[2, 1]
]
C = []
print("Matrix Addition")
for i in range(3):
C.append([])
for j in range(2):
C[i].append(A[i][j] + B[i][j])
print("%3d" % C[i][j], end='')
print()Output:
Matrix Addition
1 3
8 5
3 3