in the quiz section there is a question: “What character will be selected from the string
cool_fruit = "watermelon" using the code
cool_fruit[len(cool_fruit) - 2] ?”
I know the right answer but:
why couldn’t they write a simple cool_fruit[-2]? I mean is there any difference between this
cool_fruit[len(cool_fruit) - 2] and this cool_fruit[-2]?
Thank you in advance whoever replies to my newbie question
They were probably making it look more complex than it is on purpose and to test multiple things in one question.
so, does this mean that these two parts of a code have the same meaning?
[len(cool_fruit) - x] will evaluate to the same item in the array as
[-x], so yes they mean the same thing.
If you are asking are they doing the same thing behind the scenes? If you look at the C implementation of what deals with negative indexes what it does is take your negative value and add the length of the backing array onto it. In the case where you use len (which is also written in C) you are just doing it the other way around, getting the length of the backing array first and then subtracting the value. So pretty much, yes.