0

I’m practicing reading and writing explanations of Python code so I better understand what in the world I’m reading. I came across the below:

orderLog = [ ]
N = 5
def get_last(position):

    if position <= N and position <= len(orderLog):
     return orderLog[position * -1]

There is more code following but I need some assistance understanding the last line starting with return. Am I multiplying the parameter ‘position’ by -1 and if so.. why? Also, further down I see:

Choice = -1

Again this -1 is puzzling me.

LunaLoveDove
  • 71
  • 2
  • 8
  • 2
    Hi welcome to StackOverflow. I hope that `OrderLog` vs `orderLog` isn't a typo. To get you thinking, what happens if we access a list with a negative index (e.g. `some_list[-1]`)? – TrebledJ May 30 '19 at 15:27
  • 2
    Possible duplicate of [Negative list index?](https://stackoverflow.com/questions/11367902/negative-list-index) – Devesh Kumar Singh May 30 '19 at 15:33
  • A negative list index means you're counting _backwards_ from the _end_ of the list, instead of _forward_ from the _beginning_. i.e. `mylist[-2]` means "The second-to-last item in the list`. – John Gordon May 30 '19 at 15:34
  • @TrebledJ It was a typo! I fixed it thank you. As for your questions: I think you count the element in the list from the right. So why is there a * symbol? Am I multiplying the first element from the right with the parameter 'position'? – LunaLoveDove May 30 '19 at 15:38
  • @JohnGordon What is the purpose of the * symbol in this case than? – LunaLoveDove May 30 '19 at 15:40
  • 1
    it multiplies `position` with `-1`, – Devesh Kumar Singh May 30 '19 at 15:43
  • @LunaLoveDove That would be `orderLog[-1] * position`. Since you're doing `orderLog[position * (-1)]`, you're instead indexing `orderLog` by a _negative_ `position`. This is equivalent to `idx = position * -1; return orderLog[idx]` (or indeed, and more readably: `return orderLog[-position]`) – Adam Smith May 30 '19 at 15:45
  • 2
    It helps if you play around with the function. (E.g. try doing `orderLog = [10, 20, 30]` and calling `get_last(1)`, `get_last(2)`, `get_last(3)`. Further, what happens if you try `get_last(0)`, `get_last(4)`?) Exploration. :) – TrebledJ May 30 '19 at 15:46
  • 1
    BTW, the `position * -1` spelling is unusual. Not wrong, but most people would spell that simply as `-position`. – Mark Dickinson May 30 '19 at 15:57

1 Answers1

3

Negative list indexes count from the back. Consider this hypothetical list:

# positive indexes
#  0    1    2    3    4    5    6
 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# -7   -6   -5   -4   -3   -2   -1
# negative indexes

Multiplying by negative one simply inverts the sign of your value. I'll assume that position is usually positive, so this code reads:

If position is less than or equal to N, and position is less than or equal to the length of orderLog, then return the element that is position spaces from the end.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112