Computer >> Computer tutorials >  >> Programming >> Python

How to index and slice lists in Python?


To index or slice a list you need to use the [] operator on the list. When indexing a list, if you provide a positive integer, it fetches that index from the list counting from the left. In case of a negative index, it fetches that index from the list counting from the right. For example,

Example

my_list = ['a', 'b', 'c', 'd']
print(my_list[1])
print(my_list[-1])

Output

This will give the output −

b
d

If you want to get a part of the list, use the slicing operator. [start:stop:step]. For example,

Example

my_list = ['a', 'b', 'c', 'd']
print(my_list[1:]) #Print elements from index 1 to end
print(my_list[:2]) #Print elements from start to index 2
print(my_list[1:3]) #Print elements from index 1 to index 3
print(my_list[::2]) #Print elements from start to end using step sizes of 2

Output

This will give the output −

['b', 'c', 'd']
['a', 'b']
['b', 'c']
['a', 'c']