Python lists can contain different types of elements. They can have integers, strings, floating-point numbers, etc. They can also contain other lists:
l = [4, 5, 'hi', 3.14, ['how', 'are', 'you', '?'], 64]
print(l[2]) # hi
print(l[2][0]) # h
print(l[-1]) # 64
print(l[4]) # ['how', 'are', 'you', '?']
inner = l[4]
print(inner[1]) # are
print(l[4][1]) # are
This is an example of a list in Python that contains another list in it. The operations with the nested list are exactly the same as the ones with the outer one. One can add elements with append, or remove them with pop, etc. Therefore the indexing would work like we are accessing a nested list from within a list.
Similar to having a list of strings, where we can access each element with [index]:
greetings = [
'hi',
'hello',
'hey there',
'hey!'
]
print(greetings[0])
# hi
print(greetings[2])
# hey there
This way, we access each row separately. After that, we can access each element of the row exactly as we would access an element of a list:
print(multiplication_table[2]) # [3, 6, 9, 12, 15, 18, 21, 24, 27]
l = multiplication_table[2] # l is now [3, 6, 9, 12, 15, 18, 21, 24, 27]
print(l[0]) # 3
print(l[1]) # 6
print(l[-1]) # 27
# Or access the elements directly
print(multiplication_table[2][0]) # 3
print(multiplication_table[2][1]) # 6
print(multiplication_table[2][-1]) # 27
The first index indicates the “row” we pick from the matrix, while the second index indicates the “column”. So, the syntax of accessing an element from a 2D list is two_d[row][column].
Challenge
Given an integer n, create a 2D square list of size . You are asked to divide the square into 3 parts. The one above its diagonal, the one on the diagonal, and the one below it.
The fields above should be painted with 0, the fields on the diagonal should be painted with 1, and the ones below should be in 2.
The input of the program contains a single integer n - the size of the square.
The output of the program should contain the painted square.