Indexing & Slicing
Introduction in how to count in python
By Rotary Viper Home
In python, strings, lists and tuples may use indexing and slicing.
Indexing is splitting a piece of data into it's individual components. Then giving each component a number.
Note: Python begins indexing from 0.
String = 'R_VIPER'
'R _ V I P E R'
|0 1 2 3 4 5 6|
String[1] = '_'
String[5] = 'E'
List/Tuple (Both same)
aList = ['A', 8,'c','^',')']
'A', 8 ,'c','^',')'
|0 , 1 , 2 , 3 , 4|
aList[0] = 'A'
aList[4] = ')'
If you ran the code:
aString = 'Rotary Viper'
aList = ['A',8,'c','^',')']
print(aString[0])
print(aString[4])
print(aString[8])
print(aList[1])
print(aList[3])
Python would output:
R
r
i
8
^
Slicing is how you get the value of multiple indexes at the same time, the short way.
The syntax of slicing is similar to a superset of indexing syntax.
[Start:End:Step], when only Start or End have to be present.
Start default value is 0, End default value is len(subscriptable), Step default value is 1
Note: You can count backwards from the end of the subscriptable value by using negative numbers
If you ran the code:
aString = 'Rotary Viper'
print(aString[:1])
print(aString[1])
print(aString[:-1])
print(aString[::2])
print(aString[-1:1:-3])
Python would output:
R
o
Rotary Vipe
Rtr ie
riyt