-2

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.

Zero
  • 1
  • 1
  • 3
    `s[-1]` return last element from list(`s`).`s[-1][0]` means first element of the last item in `s` – Abdul Niyas P M Nov 01 '21 at 15:47
  • 1
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – PM 77-1 Nov 01 '21 at 15:49

1 Answers1

0

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 in x. In this case, the first element of [7, 8, 9] is 7.
Andre Nasri
  • 237
  • 1
  • 6