Accessing Elements from list¶
Let us see how we can access elements from the list
using Python as programming language.* We can access a particular element in a list
by using index l[index]
. Index starts with 0.
- We can also pass index and length up to which we want to access elements using
l[index:length]
- Index can be negative and it will provide elements from the end. We can get last n elements by using
l[-n:]
. - Let us see few examples.
In [1]:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [2]:
l[0] # getting first element
Out[2]:
1
In [3]:
l[2:4] # get elements from 3rd up to 4 elements
Out[3]:
[3, 4]
In [4]:
l[-1] # get last element
Out[4]:
10
In [5]:
l[-4:] # get last 4 elements
Out[5]:
[7, 8, 9, 10]
In [6]:
l[-5:-2] # get elements from 6th to 8th
Out[6]:
[6, 7, 8]