+ 2
why it outputs [7], please explain this code!...
numbers=[1,2,3,4,5,6,7,9,9] print(numbers[6:2:-4]) output: [7]
6 Réponses
+ 1
Sujithra Focus here :
In list[start:end:stepsize]
start is always inclusive.
end is always exclusive.
For example ,
numbers=[1,2,3,4,5,6,7,9,9]
print(numbers[6:2:-4])
#numbers[6]=7 (ALWAYS INCLUSIVE NO MATTER WHAT YOUR STEP SIZE IS)
#numbers[2]= 3(ALWAYS EXCLUSIVE IT WILL NEVER INCLUDED)
Here output will be [7 ] because it will include start which is 7 and then follow steps from back and then it will not print 3 because it is exclusive.
Try this:
numbers=[1,2,3,4,5,6,7,9,9]
print(numbers[6:0:-4])
print(numbers[0:6:4])
and u will understand better.
+ 3
Thank you sarada lakshmi and Slick
+ 2
Thank you so much DEVIL
0
Okay so broken down:
numbers[6] = 7
numbers[2] = 3
In "numbers[6:2:-4]" the "-4" means two things:
-first, the (-) tells you to reverse the list order.
-then the (4) tells you that you will be counting every 4th number in the list.
So just for an example:
numbers[6:2:-1]
[7, 6, 5, 4]
Keep in mind the 3 is not included because the list operation " list[x:y:z] " takes every number including x and up until but not including y. z is the "step"
Since (-4) is the third parameter instead of -1 like the example above, the next number to be shown in the list is 3. But since 3 is not included...
[7] is your output.
- 1
I think it's not good approach.. Coz, its a simple list, it's okay.. What if you take a large sized list.. Suppose having size 1000 or more... Always try to write code that satisfy each and every input you take...
- 1
sarada lakshmi very true, this will only work with a handful of cases. What I believe the poster was trying to understand is the output. No use writing amazing functions when you don't understand how they work.