Home > OS >  Question regarding negative indices in tuples and lists in python
Question regarding negative indices in tuples and lists in python

Time:12-19

In this program,

t=(1,2,3,4,5,6)   
print(t[-1:-4])

Why is the output:

()

and not,

(6,5,4)

This is the case with lists also. I noticed print(t[-4:-1]) doesn't give the output as () but instead gives (3, 4, 5)

What is going on here? why can't we go backwards. Please help me I've just started python, I have no background in programming!

CodePudding user response:

You have to use a negative step:

>>> t[-1:-4:-1]
(6, 5, 4)
  • Related