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?

5th Jun 2019, 9:05 PM
brigx
brigx - avatar
13 odpowiedzi
+ 2
brigx well, HonFu point was right. You can revise the lesson of slicing you will see that in [x,y] the y will never be printed simply because it's a range starting from 0. Just imagine a code with this command: print this list starting from index 1 but at the same time don't include index 1
5th Jun 2019, 9:37 PM
Mo Hani
Mo Hani - avatar
+ 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
5th Jun 2019, 9:15 PM
Mo Hani
Mo Hani - avatar
+ 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.
5th Jun 2019, 9:24 PM
HonFu
HonFu - avatar
+ 2
Mo Hani thank you i really never asked myself why for the slice [x:y] y is not in the values it makes sense now if the index starts at 0 thanks HonFu you were right all along
5th Jun 2019, 9:43 PM
brigx
brigx - avatar
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 😂
5th Jun 2019, 9:31 PM
brigx
brigx - avatar
0
Hi
5th Jun 2019, 9:44 PM
reza
reza - avatar
0
I have a problem. Who can help me?
5th Jun 2019, 9:45 PM
reza
reza - avatar
0
Where is the problem with this code? Why is not the output correct?
5th Jun 2019, 9:47 PM
reza
reza - avatar
0
reza what do you mean by output not correct
5th Jun 2019, 9:55 PM
brigx
brigx - avatar
0
brigx For example, why when I enter 8, the message (you are child) is not displayed?
5th Jun 2019, 9:59 PM
reza
reza - avatar
0
reza Please ask your question in a separate thread.
5th Jun 2019, 10:04 PM
Diego
Diego - avatar
0
reza dont nest the ifs and their statements it should work just fine
5th Jun 2019, 10:12 PM
brigx
brigx - avatar