A few days ago, while coding late at night, I had written the following (in Python) to read the first character of a string:

first_char = line[:1]

When reviewing the code right now, I thought this should instead be:

first_char = line[0]


Nope! This will fail when the string is empty.

Seems like my sleepy brain wrote better code than my awake brain xD

Or maybe I'm more tired night now ZZZ

  • 1
    Wow, had no idea about this
  • 1
    Not better. You won't have a first character.
  • 0
    @irene You're right, but what I didn't mention was that the use case was such that I was performing an action on the string if the first character was an ASCII letter. So the initial version was better for this use case.
  • 0
    Isn't this called inconsistency?
  • 0
    @faheel might be better in terms of logic, but probably not better in terms of performance 🤔
  • 3
    @hack it is consistent. Those are different functions. One is direct access, other is a more complex subrange builder.
  • 3
    Makes sense.
    There is nothing in the string to grab as a first item, but you can still slice nothing into nothing.
Your Job Suck?
Get a Better Job
Add Comment