-3
s = ''
# case 1
print(s[0])
# case 2
print(s[:1])
print(s[0:1])

In the first case I get an IndexError: string index out of range, yet the second case is perfectly correct. I'm confused; shouldn't they be the same? In both cases we're printing the character at position 0 in the string. I can get the idea of the the Error, after-all, there are no characters in the string, but I'd expect both cases to give the same Error.

Thanks!

Zephyr
  • 11,891
  • 53
  • 45
  • 80
  • 1
    The 2nd and 3rd are an empty subset, same as `s[100:2000]`, they don't give index errors. Conceptually that is fine, because lists have a way to represent no match (`[]`), while indexes do not (e.g. can't be `None`, or any value, since that could be the content of that index) – Cireo Jul 10 '20 at 22:18
  • 1
    Why do you expect an error? The documentation on slicing is quite clear on how it handles slice bounds out of range. – Prune Jul 10 '20 at 22:27

1 Answers1

1

Slices are more forgiving than indexing. If your slice indexes are out of bounds, you'll get an empty sequence or string. If you index a character that doesn't exist, you get an error as you've discovered.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622