0
Confused with python lists challenge question
What is the output of this code? squares = [0, 1, 4, 9, 16, 25, 36] print(squares [1:1:-1]) Solution : [] My answer was [1] on account that the first index of a slice is included but it seems thats wrong here.Can someone explain this to me?
13 Respuestas
+ 3
In list slicing there are usually 3 factors, [x:y:z]
The x starts the slice, y ends it but doesn't get involved in the action, z is the steps that x will take to go to y, if 1 then it will take 1 step as normal, if -1 then it will be reversed
The statement says print(squares[1:1:-1]
So it will print from 1 to 1 taking a step to the back [-1], it doesn't make any sense, Python will output an empy list as you can't move from a number to the same number and even with negative step.
I hope what i'm saying makes sense
+ 2
The ending value of a range is not included. A range of 5 goes from 0 to 4, a range of 1 has only 0 in it.
And a range/slice that goes from 1 to 1, not including the last element, effectively contains nothing.
0
I have to disagree with you HonFu the lesson on lists says the first index in a slice i.e x in [x:y] is included in the results so applying that same logic to the above question would value 1 at index 1 not be included in the slice?.I get the part where -1 means reversing the slice its just that the solution seems contradictory to the lesson....or im being thick headed 😂
0
Hi
0
I have a problem. Who can help me?
0
Where is the problem with this code?
Why is not the output correct?
0
reza what do you mean by output not correct
0
brigx
For example, why when I enter 8, the message (you are child) is not displayed?
0
reza Please ask your question in a separate thread.
0
reza dont nest the ifs and their statements it should work just fine