Tricks of List slicing

Some basic tricks in python to access list items.

Python lists are 0 indexed, and act like arrays in other programming languages.

list1 = list(range(0, 10))
print(list1)   #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list1[0])  #0
print(list1[1])  #1
print(list1[-1])  #9
print(list1[-2])  #8

#To display all elements from index 1
print(list1[1:])  #[1, 2, 3, 4, 5, 6, 7, 8, 9] 

#To display first 3 elements
print(list1[:3])  #[0, 1, 2]

#To display all elements stepping by 2
print(list1[::2])  #[0, 2, 4, 6, 8]

#To display all elements in reverse order
print(list1[::-1])  #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

#To display all elements in reverse order excluding the last item(which is at 0 index in inverse order)
print(list1[-1:0:-1])  #[9, 8, 7, 6, 5, 4, 3, 2, 1]

#To display elements between index 5 and 8
print(list1[5:8])  #[5, 6, 7]

#To display elements between index 1 and 10
print(list1[1:10])  #[1, 2, 3, 4, 5, 6, 7, 8, 9]