1.4 Indexing and Slicing

1.4.1 1 D Python List

my_list = ['a0','b1','c2','d3','e4','f5','g6','h7']
Syntax Result Note
my_list[0] First element 'a0'
my_list[-1] Last element 'h7'
my_list[0:3] Index 0 to 2 ['a0','b1','c2'] Give \(3-0 = 3\) elements
my_list[1:6] Index 1 to 2 ['b1', 'c2', 'd3', 'e4', 'f5'] Give \(6-1 = 5\) elements
my_list[1:6:2] Index 1 to 5 in steps of 2 ['b1', 'd3', 'f5'] Give every other of \(6-1 = 5\) elements
my_list[1:] Index 1 to the end ['b1', 'c2', 'd3', 'e4', 'f5', 'g6', 'h7'] Give \(length-1 = 7\) elements
my_list[:5] Index 0 to 5 ['a0', 'b1', 'c2', 'd3', 'e4'] Give \(5-0 = 5\) elements
my_list[5:2:-1] Index 5 to 3 ['f5', 'e4', 'd3'] Give \(5-2 = 3\) elements
my_list[::-1] Reverses the list ['h7', 'g6', 'f5', 'e4', 'd3', 'c2', 'b1', 'a0']

1.4.2 2D Numpy Array

import pandas as np
my_list_np = np.array([['A0', 'A1', 'A2', 'A3', 'A4'],
                       ['B0', 'B1', 'B2', 'B3', 'B4'],
                       ['C0', 'C1', 'C2', 'C3', 'C4']])
Syntax Result Result
my_list_np[0] 1st row ['A0','A1','A2','A3','A4']
my_list_np[1] 2nd row ['B0','B1','B2','B3','B4']
my_list_np[0,1] 1st row, 2nd element A1
my_list_np[1,1:3] 2nd row, elements 2 to 3 ['B2','B3','B4']
my_list_np[1,1:] 2nd row, elements 2 to 3 ['A0','B1','C2']