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.
KNOWLEDGE QUIZ
Concatenation and repetition
+ concatenates two lists. * repeats a list.
lst = [1, 2, 3] + [4, 5, 6]
print(lst)
lst = [1, 2, 3] * 3
print(lst)[1, 2, 3] + [4] creates a new list, while methods such as append() and insert() mutate the original list.
List workbench: operate on real elements
Choose a method, enter only the arguments it needs, and watch both the list and return value change.
append() → return: —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)
print(lst[2:7])
print(lst[:5])
print(lst[3:])
print(lst[::2])Drag a slice to match the challenge
Drag across the cells from start toward end. The stop handle is exclusive, just like Python slicing.
Press a cell and drag horizontally. The stop index is immediately after the last blue cell and is excluded.
No selectionKNOWLEDGE QUIZ
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])
print(matrix[1][2])matrix[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 A and B are both m × n matrices, then the result matrix is also m × n. “Element by element” means row i, column j is only combined with row i, column j from the other matrix.
Written as complete mathematical matrices, the element-by-element addition in the code is:
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 3Move all zeroes to the end of a list
Read a list of integers, keep non-zero values in order at the front, and move every zero to the end.
- Read a space-separated list of integers.
- Keep the non-zero values in their original order.
- Print the transformed list.