Prev: List slicing | Next: List functions & methods
L1 = [[1,2,3], [4], [5,6]]
print(L1)
print(L1[1])
- a list, an integer and a string
L2 = [[1,20], 200, 'A']
print(L2)
print(L2[0])
L1 = [[1,2,3],[4,5,6],[7,8,9]]
print(L1)
print()
#printing L1 in pseudo "rows x columns" format
for row in L1: #No index is required!
print(row)
L2 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print(L2)
print()
#printing L2 in pseudo "rows x columns" format
for row in L2: # No index is required!
print(row)
L3 = [[1,2,3],[4],[7,8],[10,11,12,13,14]]
print(L3)
print()
#printing L3 in pseudo "rows x columns" format
for row in L3: #No index is required!
print(row)
a = [ [ 1, 2, 3 ] , [ 4, 5, 67 ] ]
for i in a:
print(i)
alist = [[0 for i in range(5)] for k in range(3)]
alist
The above comprehension works as follows:
for x in alist:
print(x)
blist = [[1 for i in range(2)] for k in range(4)]
for x in blist:
print(x)
clist = [[i+1 for i in range(2)] if k%2==0 else [i+3 for i in range(3)] for k in range(4)]
for row in clist:
print(row)
- index [1] refers to the second item of L2 which is the [4,5,6] list
- double index [1][2] refers to the third item of the L1[1] list
L1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print(L1[1])
print(L1[1][2])
#print(blist[1,2]) #this syntax is not accepted for indexing 2D lists
- L2[1][2] returns the 3rd item (index 2) of the L2[1] item
- L2[1] returns the 2nd (index 1) item of L2
- L2[1:2] returns a slice containing only the 2nd (index 1) item of L2
L2 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print(L2[1][2])
print(L2[1])
print(L2[1:2])
a3dlist = [[[1 if k==n else 0 for k in range(4)] for n in range(4)] for m in range(2)]
for _2d in a3dlist:
for row in _2d:
print(row)
print()
- Begin from the inner loop (k iterator) that defines a 4-item list with values depending on the conditional expression: "1 if k==n else 0" ...
- ..then move to the middle loop (n iterator) which describes 4 items of the 'inner loop shape'; so far a 2D list of 4X4 shape has been described..
- ..and finally move to the outer loop (m iterator) which defines that two elements of 4X4 shape are constructed
... when seriously working with data you are most likely to use advanced structures like 'nd-array' (in numpy package) and/or 'DataFrame' (in pandas)
. Free learning material
. See full copyright and disclaimer notice