A deep dive into indexing and slicing over ordered collections .In this article, we are going to explore how both indexing and slicing work, and how they can be used in order to write cleaner and more Pythonic code.
In Python, the elements of ordered sequences like strings or lists can be -individually- accessed through their indices. This can be achieved by providing the numerical index of the element we wish to extract from the sequence. Additionally, Python supports slicing that is a characteristic that lets us extract a subset of the original sequence object.
In this article, we are going to explore how both indexing and slicing work, and how they can be used in order to write cleaner and more Pythonic code.
Like most programming languages, Python offsets start at position 0 and end at position N-1, where N is defined to be the total length of the sequence. For instance, the total length of the string Hello
is equal to 5 and each individual character can be accessed through indices 0 to 4 as shown in the diagram below:
Indices in Python
Now you can programmatically access individual characters in the string, by providing the corresponding offset you wish to fetch, enclosed in square brackets:
>>> my_string = 'Hello'
>>> print(my_string[0])
'H'
>>> print(my_string[2])
'l'
>>> print(my_string[3])
'l'
🔵 Intellipaat Data Science with Python course: https://intellipaat.com/python-for-data-science-training/In this Data Science With Python Training video, you...
Enroll in our Data Science with Python training in Chennai. Best Data Science with Python Training courses in Chennai for 100% Job Placements Support.
🔥Intellipaat Python for Data Science Course: https://intellipaat.com/python-for-data-science-training/In this python for data science video you will learn e...
Master Applied Data Science with Python and get noticed by the top Hiring Companies with IgmGuru's Data Science with Python Certification Program. Enroll Now
Become a data analysis expert using the R programming language in this [data science](https://360digitmg.com/usa/data-science-using-python-and-r-programming-in-dallas "data science") certification training in Dallas, TX. You will master data...