Class 11-Python Lists-Slicing
Class 11-Python Lists-Slicing
ARTIFICIAL INTELLIGENCE
PYTHON – SLICING IN LISTS
LIST SLICING
For example, if [5,2,3,8,9] is a list, then some of its slices can be [5,2,3], [3,8,9], [2], [2,9],
[9,8,3,2] etc.
In Python we can extract any slice of a list by specifying the list name, start index, stop
index, and step size
syntax:
listName[start:stop:step]
This will extract the elements of the list starting from index start till (but not including)
index stop in steps of step.
• List=['G','O','O','D','M','O‘,'R','N','I','N','G']
• print(List)
• print(List[:]) #prints all list elements
• print(List[5] #prints ['O', 'R', 'N', 'I', 'N', 'G']
•
• Sliced_List=List[3:8]
• print(Sliced_List) #['D', 'M', 'O', 'R', 'N']
• Further we way use the above general syntax in different ways to slice the strings:
Note:
• In the above syntax start value is included and end value is excluded.
LIST SLICING EXAMPLES
INTERESTING INFERENCE IN LIST SLICING
Giving upper limit way beyond the size of the list. But,
Python return elements from list falling in range 3
onwards <30.
a.
day= ['f','r','i','d','a','y']
print(a[-1])
print(a[-6])
b.
n_list=[“Happy”,[2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])