I have some programming experience in other languages, but I've been taking the Core Python course from Pluralsight to contrast the language features. In the iterables section of the course, the instructor created this function that uses the EAFP principle to raise an exception if the iterable argument is empty:
def first(iterable):
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise ValueError("iterable is empty")
I saw this and thought, "couldn't I just raise that exception in an else clause? So I wrote this function:
def first(iterable):
if(len(iterable) == 0):
raise ValueError("iterable is empty")
else:
return iterable[0]
When writing this post, I found this Stack Overflow question about the implicit boolness of an empty list and thought I could refactor my code to make it even more pythonic:
def first(iterable):
if not iterable:
raise ValueError("iterable is empty")
else:
return iterable[0]
They seem to work the same way, and mine still uses the EAFP principle, right? Is the first one faster? Or is it just a demonstration of the iter() and next() functions?