In this post, we will understand concepts around slicing lists in Python. Let's say, I have names of my friends stored in a Python List
list_friends = ["Irfan", "Jitu", "Ketan", "Ravi", "Rohan", "Zephyr"]
If I ask you , give me 4th and 5th friend in the list, this is how it is done.
list_friends[4:6]
---> ['Rohan', 'Zephyr']
If I say, give me alternate names of friends starting from Irfan.
list_friends[0:5:2]
----> ['Irfan', 'Ketan', 'Rohan']
The slice operator is in the form as given below
start:end:step
Interpret this as "Go from start index to end index (but exclude element at end index) with a step size of step"
In the previous example, we went from 0 to 5 with a step size of 2
If start index is not given, Python assumes it as 0
If end index is not give, Python assumes it as last index (equal to length of list-1)
list_friends[::2]
-->['Irfan', 'Ketan', 'Rohan']
The above code will give the same output as in the previous example.
Comments
Post a Comment