-1
foo = 'eggs'

foo[:1] # the same is foo[0]
foo[-1:] # the same is foo[-1]

Is there any advantage of one of these ways?

I ran into this over here https://hg.python.org/cpython/file/3.4/Lib/xml/etree/ElementPath.py#l254

UPD. Can you go to the link? The variable path is a string there. And I was confused, why they were using a slice instead of a concreate index.

if path[-1:] == "/":
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • this will help you to understand.. [Explain Python's slice notation][1] [1]: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – Shri Nov 11 '14 at 09:28
  • Thank you. I know how it works, but the piece of code above is a reason I was confused. See the link in my question. Where path is a string. – Aleksandr Zhuravlёv Nov 11 '14 at 09:47
  • 1
    The difference is what happens when the string is empty: extracting a list returns an empty string, while getting a concrete element will raise an error. – Ethan Furman Nov 11 '14 at 19:07

3 Answers3

2

Strings are a special case with slices since an slice return a str, but asking for a concrete index also returns a str. Unlike C, C++, Java, we don't have a char datatype in Python.

You can see the real difference on a plain list. Using a semicolon returns a slice, which is a list, while a concrete index returns a single element of the list; in this case, an int. That is, the data type is different.

>>> foo = [66,67,68,69]
>>> foo[:1]
[66]
>>> foo[-1:]
[69]
>>> foo[0]
66
>>> foo[-1]
69
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
vz0
  • 32,345
  • 7
  • 44
  • 77
1

slicing works like this:

#bring everything from start to end as list
foo[::]

#bring last item as list
foo[-1:]

#careful not to confuse with ->bring last item
foo[-1]

slicing basically works like this

foo[starting_point:ending_point:step]
#default starting point=0
#default end point is len(foo)
#default step=1

Difference between checking foo[-1] and foo[-1:] besides the fact that the first returns an item(immutable) and the second a list(mutable), is that if foo[] is empty, foo[-1] will raise an IndexError while foo[-1:] will return an empty list.

On your link now: https://hg.python.org/cpython/file/3.4/Lib/xml/etree/ElementPath.py#l254

We're talking about strings here so result of path[-1] and path[-1:] will be a string. So the reason why path[-1:] is preferred is because if path="", path[-1] will raise the IndexError while path[-1:] will return ""

0

str is a special case, because both slicing and element access will return another str. The difference is what happens when the string is empty: extracting a list returns an empty string, while getting a concrete element will raise an error.

--> test = 'hello'
--> test[0]
'h'
--> test[:1]
'h'
--> empty = ''
--> empty[:1]
''
--> empty[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237