+ 1

output of lists slicing.....?? HOW

squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[1:-1]) OUTPUT [ 1, 4, 9, 16, 25, 36, 49, 64] sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[1:7:-1]) OUTPUT [] sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1]) output [49, 36]

6th Apr 2018, 6:18 PM
Smriti Rastogi
Smriti Rastogi - avatar
3 Respuestas
+ 4
Some a bit tricky things here are: 1. List indexes are always not negative (positive or 0). list index [-1] is just an alias for [len(list)-1], so it is always equal or greater then zero. 2. Slice step could be both positive and negative. So you can walk throught the list forward or backward. That is why you have >>> sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> print(sqs[7:5:-1]) [49, 36] 3. With negative step, you obviously can not go forward. That is why you got an empty list: >>> sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> print(sqs[1:7:-1]) [] This is true with an opposite case: >>> sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> print(sqs[7:5:1]) [] - you can not go back stepping forward. Note ,that you got a list, not a None object, because you created list by the sqs[...] statement, but got an empty sequence of elements in it.
7th Apr 2018, 10:28 AM
strawdog
strawdog - avatar
- 1
Answer=5
27th Mar 2022, 6:31 PM
Binara Tennakoon
- 3
slicing is kind of self explanatory if you count the numbers
6th Apr 2018, 8:05 PM
Markus Kaleton
Markus Kaleton - avatar