We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Can you explain the functionality of [::-1] used in your code? I figured it reverses the list order but could you expound on what the different ':' are for and '-1' is doing exactly to cause to flip the order?

foo[i:j:k] gives a slice of list foo from i to j (but not including j) by step k

when i or j is omitted, it takes the whole range, so [::1] means "from first to last". but if k is negative, the order is reversed, so [::-1] means "from last to first"

it's a cute way of getting the list in reverse order, in other words

so then he uses the [1] index to get the second element in the reversed list, which gives the runner-up value

could just have used [-2] instead of forcing the list to be reversed

## Find the Runner-Up Score!

You are viewing a single comment's thread. Return to all comments →

Can you explain the functionality of [::-1] used in your code? I figured it reverses the list order but could you expound on what the different ':' are for and '-1' is doing exactly to cause to flip the order?

foo[i:j:k] gives a slice of list foo from i to j (but not including j) by step k

when i or j is omitted, it takes the whole range, so [::1] means "from first to last". but if k is negative, the order is reversed, so [::-1] means "from last to first"

it's a cute way of getting the list in reverse order, in other words

so then he uses the [1] index to get the second element in the reversed list, which gives the runner-up value

could just have used [-2] instead of forcing the list to be reversed