4

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]
1
  • 1
    With s[-1:-len(s)-1:-1] Commented May 24, 2020 at 21:49

3 Answers 3

3

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])

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.