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] <= el):

el is an int variable from and array.

2

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 in x. In this case, the first element of [7, 8, 9] is 7.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest