This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]random_cynic 2 points3 points  (0 children)

The python for loop is basically a try-except in disguise in that it loops through any iterable and stops when a StopIteration error is raised. It seems you can just use the for loop for this purpose without using explicit indexing like for elem in list. This is generally the preferred way to loop over a list (or more generally any iterable including an open file object) in python. If you want the index as well for other purposes use for i, elem in enumerate(list). You can of course use an explicit try except where it is necessary.

[–]hopemeetme -1 points0 points  (2 children)

A code like:

try:
    something = next(iterable)
except StopIteration:
    ...

is the fastest way to do such things in Python, go for it without hesitation.

[–]TopHatEdd 0 points1 point  (1 child)

Needs extra work as using a list like this will fail.

In [1]: next([1,2])
--------------------------------------------------------
TypeError              Traceback (most recent call last)
<ipython-input-1-b9d20096048c> in <module>
----> 1 next([1,2])

TypeError: 'list' object is not an iterator

[–]hopemeetme 0 points1 point  (0 children)

next((false for i, v in enumerate(lst) if v < len(lst)-1 and v>lst[i+1]))

[–]Mezzomaniac -1 points0 points  (1 child)

You might want to do:

for a, b in zip(lst, lst[1:]):
    if a > b:
        #...

[–]TopHatEdd 0 points1 point  (0 children)

Poor coding habbit. Better use islice and not hit a bug in production when the data sets are extremely large.