-2

Why does this not print the last element in the list.

>>> a_lst = [1,2,3,4,5,6]
>>> print a_lst[-1]
6
>>> print a_lst[0:-1]
[1, 2, 3, 4, 5]

I can see that if I just do a_lst[-1] it returns the expected last element. But when I try to use it in a range [0:-1] it actually returns the penultimate element?

PerryDaPlatypus
  • 735
  • 1
  • 8
  • 17

1 Answers1

2

a_lst[0:-1] it is up to and NOT including the last element, a_lst[-1] is just the last element.

a_lst[0:] would get all the elements.

When you slice a list it goes a_list[start:stop-1:step], where the step is optional

In [32]: l[0:-1]
Out[32]: [1, 2, 3, 4, 5]  # all but last element

In [33]: l[0::2]  # start at first and step of 2
Out[33]: [1, 3, 5]

In [34]: l[0::3]  # start at first and step of 3
Out[34]: [1, 4]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thank you Padraic, for taking the time to answer, and help me out. I really appreciate it. Sorry to everyone else who down voted my question. I searched, but apparently not hard enough. Apoplogies. – PerryDaPlatypus Jul 14 '14 at 16:51