+ 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]
3 Answers
+ 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.
- 1
Answer=5
- 3
slicing is kind of self explanatory if you count the numbers