The correct order of commands is as follows:
values = []
values.append(1)
values.append(3)
values.append(5)
print('first time:', values)
values = values[1:]
print('second time:', values)
first time: [1, 3, 5] second time: [3, 5]
The list values[low:high] has high - low elements.
For example, values[1:4] has the 3 elements values[1], values[2], and values[3].
Note that the expression will only work if high is less than the total length of the list values.
m.-1.-N, which represents the first element.del values[-N] removes the first (zeroth) element from the list.values[:-1]First we assign the string lithium to the variable element, which displays nothing.
element = 'lithium'
Next, we ask to print the slice element[-1:3].
But the index -1 for element corresponds to index 6, because the length of element is 7, and 7-1 is famously 6.
So we are effectively asking for element[6:3], which is an empty slice because the "low" value of 6 is higher than the "high" value of 3.
print(element[-1:3])
Lastly we ask to print element[0:20].
Knowing that elements only has length 7, so the final index is 6, you might expect an error to occur here (as there is no item at indices 7 through 19 = 20-1).
However we are asking for a slice of the list element, and when a slice includes an index that is not present, we get an empty list back.
As such, the slice element[0:20] is identical to element[0:7] or even just element[0:] - the "extra indices" we've asked for above 6 simply give us back an empty list, so the output is identical to when we just ask for the whole list.
print(element[0:20])
# for clarity, here's element[0:7]:
print('element[0:7]: ', element[0:7])
# and here's what happens when we start our slice beyond the range of indices in our list
print('elemnt[7:20]: ', element[7:20])
lithium element[0:7]: lithium elemnt[7:20]: