Meaning of Stack[-1][0] in Python
I'm New to Python and I'm Trying to Understand a Piece of Code but I Don't Understand What the S[-1][0] Means. S = [ ]; While(Len(S)>0 and S[-1][0]
I'm new to python and I'm trying to understand a piece of code but I don't understand what the s[-1][0] means.
s = [ ];
while(len(s)>0 and s[-1][0] <= el):
el is an int variable from and array.
1 Answer
Python supports negative indexing of iterables, e.g. lists. Let's assume that we have the following:
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(x[-1][0])
Output:
7
x[-1]returns the last element of the list, i.e. the list[7, 8, 9]. Similarly,x[-2]returns the second to last element of the list, and so on.x[-1][0]returns the first element of the last list inx. In this case, the first element of[7, 8, 9]is7.