- 1
How to inverse a List?
In List slices we can print out from which index to which index with X steps. When we use [first_index:second_index:-num] it is not working and retrieve None. my question is how we can inverse a range of indices in a list from first_index to last_index by a negative number step. for instance: sqs=[0,3,5,30,13,15,36,1,12,9,24] print(sqs[2:8:-2]) my desired output (in a single command): [1,15,30] any idea? Thanks in advance.
4 Réponses
+ 1
As for your code, if you start at 2 and move backwards, you will never reach 8 - that's why you get an empty list (it's not None, it's an empty list!):
>>> sqs=[0,3,5,30,13,15,36,1,12,9,24]
>>> print(sqs[2:8:-2])
[]
Try this:
>>> print(sqs[7:2:-2])
[1, 15, 30]
0
sqs[::-1] should reverse the list. is this what you mean by inverse a list? I've seen inverse on matrices and numbers. first time seeing inverse on a list.
0
Thanks Bogdan Sass
It was what I exactly wanted but i didn't try it.
Thanks again.
Warm regards.
0
print(sq[::-1]) it will inverse the list with square of the number !!