Reputation: 547
I was reading the source code of the Python xml.etree.ElementTree module (https://github.com/python/cpython/blob/master/Lib/xml/etree/ElementTree.py) and I came across an interesting use of slices. The authors wrote the following code:
prefix = text[:1]
Which as far as I can tell is identical to:
try:
prefix = text[0]
except IndexError:
prefix = text
Are these code snippets identical? What are the benefits and detriments of using [:1] in place of [0]?
Upvotes: 0
Views: 70
Reputation: 3591
If your question is scoped by string usage only, then yes – they are identical. You get benefit from less code, but second snippet is more pythonic and explicit.
Upvotes: 0
Reputation: 62083
One other difference: text[0]
results in an exception if text
is an empty list, while text[:1]
returns an empty list. Similarly, indexing an empty string will give you an exception while slicing returns an empty string.
Upvotes: 2
Reputation: 2365
The difference is in the output format:
a[:1]
returns a list with the first element. While a[0]
returns the first element.
>>> a = [1, 2, 3, 4, 5, 6]
>>> a[:1]
[1]
>>> a[0]
1
Upvotes: 2