how can get the 3rd line to do the same as the second line?
list = [1,2,3,4,5,6,7,8,9,10]
print(list[::-1])
print(list[-1:0:-1])
this is the result i got:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2]
You should omit 0 here:
print(list[-1:0:-1])
and write it as
print(list[-1::-1])
or place None:
print(list[-1:None:-1])
The reason is: when you omit the stop value (or substitute None) in a "3 colon-seperators", this will happen:
If i or j are omitted or
None, they become “end” values (which end depends on the sign of k).
where j here corresponds to the stop value (and i is the start i.e. [i:j:k])
Use None:
>>> list[-1:None:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
or
>>> list[None:None:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
You could use -len(list)-1, but None is simpler and doesn't require any computation.
BTW list is a bad variable name since it shadows the builtin list.
You can use following ways of list slicing to achieve required result.
list = [1,2,3,4,5,6,7,8,9,10]
#Use Blank:
print(list[::-1])
print(list[-1::-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#Use None:
print(list[:None:-1])
print(list[None:None:-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#Use Boolean:
print(list[-True::-True])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#Use Boolean:
print(list[~False::-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#Use of Length function:
print(list[:-(len(list)+1):-1])
#output
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
s[-1:-len(s)-1:-1]