Lists are an integral feature of Python. The language provides a vast range of different utilities which make list manipulation simple and efficient.
With the introduction of slicing, a sublist can be easily accessed using the indexing convention.
A list can be sliced in the following way:
myList[start:end]
Keep in mind that start
and end
are indices of the list. The value at the end
index is not included in the sublist. Slicing also works with strings.
myList = range(10) # A list from 0 to 9print myListprint myList[2:7]myString = "Hello World"print myStringprint myString[6:11] # Accessing the "World" substring
It is not necessary to define the start
and end
indices explicitly.
If the end
is left blank, the resulting sublist would start from the start
index and end at the last element in the list.
If the start
index is omitted instead, the sublist would begin from the first element and stop at the end
index, but not including the element at the end
index.
myList = range(10) # A list from 0 to 9print myListprint myList[3:]print myList[:6]print myList[:] # Prints the whole listmyString = "Hello World"print myStringprint myString[4:]print myString[:8]
So far, the sublists have only contained continuous elements. However, a step can be defined which tells the compiler to “step” over certain elements.
The step
is defined after the end
index:
myList[start:end:step]
myList = range(10)print myListprint myList[0:10:3] # Steps three elements ahead each timeprint myList[4::2] # Omit the end index and step two elements ahead
Assigning new values to a sliced sublist will alter the content of the original list as well.
myList = range(10)print myListmyList[2:5] = [41, 83, 17]print myList
A reversed sublist or substring can be obtained by switching the start
and end
indices. In this case, a negative step
would have to be provided:
myList = range(10)print myList# The reversed list from the 9th index to the 5th indexprint myList[9:5:-1]
A negative index begins from the end of the list. So, for a list of 10 elements, list[-2]
would imply list[10-2]
myList = range(10)print myListprint myList[-3:] # Starts from the 7th index and goes till the endprint myList[-3::-1] # Starts from the 7th index and goes till the end
Free Resources