-2

I have just started learning python basics. Going through python basics, I am stuck in this iteration algorithm and I don't have any idea how it works. It is very simple I know but as a new programmer, I don't have a hobby of writing code daily.

Here is the Code

for i in inputlist:
    if i > outputlist[-1]:
        outputlist.append(i)

return outputlist

What is output list is actually doing what is the meaning of -1 there

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
  • 1
    For each element of the list, it compares it to the last element added to outputlist. If its greater, it adds it to output list. So it essentially drop-sorts the inputlist. – Dillon Davis Jul 06 '18 at 06:32

1 Answers1

1

This code is traversing the inputlist elements one by one and if the current element i in inputlist is greater than the last element in outputlist, then i will be appended to output list.

outputlist will be an increasing subsequence of inputlist.

I assume the code can be as such:

def f(inputlist):
    outputlist = []

    if inputlist:
        outputlist.append(inputlist[0])

    for i in inputlist:
        if i > outputlist[-1]:
            outputlist.append(i)

    return outputlist

The syntax outputlist[-1] gets the last element of outputlist. In most other languages it'll be equivalent to outputlist[len(outputlist) - 1] (considering 0-based list indexing).

As rightly pointed out in the comments, outputlist cannot be empty in the beginning otherwise we'll get IndexError.

Shubham
  • 2,847
  • 4
  • 24
  • 37
  • `IndexError:` output list is empty when you index the last element. – Dillon Davis Jul 06 '18 at 06:35
  • why It will show Indexerror – ayush bhambore Jul 06 '18 at 06:45
  • I would argue that appending a zero is misleading and incorrect. It will cause negative values in inputlist to be disregarded, and will always have a zero regardless of whether inputlist contains zero. – Dillon Davis Jul 06 '18 at 06:49
  • @ayushbhambore If you try to index an empty list, you get `IndexError` in Python. And in my previous edit, the `outputlist` was initially empty and I was indexing it with `outputlist[-1]`. – Shubham Jul 06 '18 at 07:44