+ 1

List anomaly in Python

Hello, I've recently had a pretty peculiar task in a Python challenge. It had the following code: a = [1, 2, 0, 3, 4] for x in range(len(a)): if x >= 4: print(a[-a[-1]]) What this code does is pretty clear to me. But what drew my attention was the last line and the "-a" thing there. Looks like it works this way: - first we take our list "a" - we "reverse" it with this a[-a] thing - and then we specify the penultimate item from the reversed version of the list with a[-a[-1]] So it's basically the same as a[1]. a[-a] doesn't work on its own, it seems to require a particular item indication. What is this "-a" thing called? How can it be used? Where can I learn more about it? (sorry, I just don't know how to Google it)

14th Apr 2022, 7:08 PM
chalupa bazooka
chalupa bazooka - avatar
10 Respuestas
+ 8
It's not weird, it's making the list value negative. a[-a[-1]] a[-1] == 4 but because the negative in front of 'a' it's -4 a[-4] == 2 Look at this code: https://code.sololearn.com/cy2xE91f5cRQ/?ref=app
14th Apr 2022, 7:16 PM
Slick
Slick - avatar
+ 3
"-" just negates the number at a[-1]
14th Apr 2022, 7:14 PM
Lisa
Lisa - avatar
+ 2
First a=[1,2,0,3,4] Here there is a[-a[-1]] First let us keep -a aside Here let's start from inside i.e a[-1] =4 Now a[-a[-1]]= a[-4] =>2 Hope it helps :)
15th Apr 2022, 3:17 AM
UNKNOWN
+ 2
Basic thing to remember is to always resolve the innermost groupings (parentheses/brackets) first, working your way outward, when evaluating a nested expression.
15th Apr 2022, 2:03 PM
Erik
+ 1
Slick, thanks for the code example! So, for instance, a[-a[2]] it's just a more complicated way to say a[-3], right?
14th Apr 2022, 7:34 PM
chalupa bazooka
chalupa bazooka - avatar
+ 1
No worries, and that's correct if you're referring to my example
14th Apr 2022, 7:35 PM
Slick
Slick - avatar
+ 1
UNKNOWN, thank you! That's a very clear way to explain it!
15th Apr 2022, 5:51 AM
chalupa bazooka
chalupa bazooka - avatar
+ 1
Erik, that's a great advice, thanks! I usually stick to it but this time I got really confused with the minus before the variable.
15th Apr 2022, 2:20 PM
chalupa bazooka
chalupa bazooka - avatar
0
Lisa, thanks for the fast response! But would that not return -4, if it was just a negation? It returns 2 for me. Or perhaps I just got your response wrongly, sorry.
14th Apr 2022, 7:37 PM
chalupa bazooka
chalupa bazooka - avatar
0
Lisa, nevermind, now I understand what you meant. So it's basically like this: a[-a[-1]] == a[-4] Yeah, so that was just an awkward way to mean something as simple as that 😅
14th Apr 2022, 7:42 PM
chalupa bazooka
chalupa bazooka - avatar