You can use slices to partially retrieve the elements of a list.
Get elements of indexes 1-3
>>> a = [1,2,3,4,5,6,7,8,9]
>>> a[1:4]
[2, 3, 4]
** * The end is the value of index +1 **
>>> a = [1,2,3,4,5,6,7,8,9]
>>> a[1:8:2] #Elements with indexes 1 to 7 in 2 steps
[2, 4, 6, 8]
>>> a = [1,2,3,4,5,6,7,8,9]
>>> a[-1]
9
-1 is the last element, -2 is the second element from the back, and -3 is. .. .. (Omitted)
>>> a[-2]
8
>>> a[-3]
7
>>> a[-4]
6
>>> a = [1,2,3,4,5,6,7,8,9]
>>> a[5:20]
[6, 7, 8, 9]
>>> a[-100:4]
[1, 2, 3, 4]
If the beginning is omitted, the "first" element is shown.
>>> a[0:4]
[1, 2, 3, 4]
When
>>> a[:4]
[1, 2, 3, 4]
Is synonymous with
If the end is omitted, the "last" element is shown.
>>> a[5:len(a)]
[6, 7, 8, 9]
When
>>> a[5:]
[6, 7, 8, 9]
Is synonymous with
>>> a = [1,2,3,4,5,6,7,8,9]
>>> a[-4:]
[6, 7, 8, 9]
I can do anything
>>> a[0:len(a)]
When
>>> a[:]
Or
>>> a[::]
Is synonymous with
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[0:len(a)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = a[-5:]
>>> b
[5, 6, 7, 8, 9]
>>> b[1] = 60
>>> b
[5, 60, 7, 8, 9]
#The original list is a separate instance from the copied list, so it is not affected by the changes.
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
As mentioned earlier, steps could be specified for slices.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[3:8:2] #Indexes 3-7 in 2 steps
[4, 6, 8]
You can slice in the opposite direction by doing the following.
>>> a[7:2:-2] #Index 7 ~ 3-In 2 steps
[8, 6, 4]
If you specify all the ranges and make a minus step, the elements will be reversed.
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Similarly for the character string as follows.
>>> txt = '123456789'
>>> txt[1:4]
'234'
>>> txt[-1]
'9'
>>> txt[:4]
'1234'
>>> txt[5:]
'6789'
>>> txt[::-1]
'987654321'
Recommended Posts