Search code examples
pythonfor-looprangeiterationenumerate

Short for 'for i in range(1,len(a)):' in python


In python, is there a short way of writing for i in range(len(l)):?

I know I can use for i,_ in enumerate(l):, but I want to know if there's another way (without the _).

Please don't say for v in l because I need the indices (for example to compare consecutive values l[i]==l[i+1]).


Solution

  • You can make it shorter by defining a function:

    def r(lst):
        return range(len(lst))
    

    and then:

    for i in r(l):
        ...
    

    Which is 9 characters shorter!