Page 410 - Ai_417_V3.0_C9_Flipbook
P. 410
Comparing the Lists
The comparison of the lists is done using comparison operators >, <, >=, <=, != and ==. These operators
compare the elements in lexicographical order (alphabetically order). For example, if corresponding elements
are same, it goes to the next element, and so on until it finds elements that differ. For example,
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l3 = [1, 2, [3]]
l4 = [1.0, 2.0, 3,0]
print(l1 == l2) #True
print(l1 > l2) #False
print(l1 == l3) #False
print(l1 == l4) #False
print([1, 2, 6] < [1, 2, 5]) #False
print([1, 2, 6] != [1, 2, 5]) #True
print([1, 2, 6] > [1, 2, 5]) #True
Slicing a List
Slicing a list means accessing a specific portion of a list. This can be done by using a range of index values with
start index number, end index number separated by colon. We can use both forward index and backward index
to specify the range of slicing in a list. Some important points to consider to do slicing in a list are:
• Elements from beginning to a range - list[ : index] or [ : -index]
• Elements from specific Index till the end - list[index:]
• Elements within a range - list[start index : end index]
• Elements within range using step value - list[start index : end index : step value]
• Whole list in forward order - list[ : ] OR list[::] or list[0: len(list)]
• Whole list in reverse order - list[ : : -1].
For example,
word = ['E', 'D', 'U', 'C', 'A', 'T', 'I', 'O', 'N']
Forward Indexing 0 1 2 3 4 5 6 7 8
E D U C A T I O N
–9 –8 –7 –6 –5 –4 –3 –2 –1 Backward Indexing
Examples Commands Output
To display the whole list print(word[:]) ['E', 'D', 'U', 'C', 'A', 'T', 'I', 'O', 'N']
or
print(word[::])
or
print(word[0:])
or
print(word[-9:])
408 Touchpad Artificial Intelligence (Ver. 3.0)-IX

