Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop in python with counter?

How can I create a for loop with a counter? I have a list, and I want to read an element after each n elements. I'd initially done this

for i in enumerate(n):
    print(i)

But as expected it prints every element instead of every nth element, what would be the Python way of solving this?

like image 519
Ahijit Avatar asked Oct 29 '25 23:10

Ahijit


1 Answers

I am not sure wich kind of value is n but usually there are this ways: (for me, n is a list)

for index, item in enumerate(n):
   if index % nth == 0: # If the output is not like you want, try doing (index + 1), or enumerate(n, start=1).
       print(item)

Other way could be:

for index in range(0, len(n), nth): # Only work with sequences
   print(n[index]) # If the output is not like you want, try doing n[index + 1]

Or:

for item in n[::nth]: # Low perfomance and hight memory consumption warning!! Only work with sequences
    print(item)

Even you can combine the first one with the last one:

for i, item in list(enumerate(n))[::nth]: # Huge low perfomance warning!!!
    print(item)

But I'm not sure if that has an advantage...

Also, if you are willing to make a function, you could do something similar to the enumerate function:

def myEnumerate(sequence, start=0, jump=1):
    n = start
    j = start // Or j = 0, that is your decision.
    for elem in sequence:
        if j % jump == 0:
            yield n, elem
            n += 1
        j += 1

for index, item in myEnumerate(n, jump=1):
    print(item)

Personally, I wouldn't do this last one. I'm not sure why but it's a feeling.

Perfomance test

n = 'a b c d e f g h i j k l m n ñ o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 ! " · $ % & / ( ) = ? ¿ Ç ç } { [ ] ; : _ ¨ ^ * ` + ´ - . , º ª \ /'.split(" ")
nth = 3    
def a():
    for i, item in enumerate(n):
       if i % nth == 0:
           item       
def b():
    for item in range(0, len(n), nth):
       n[item]           
def c():
    for item in n[::nth]:
        item    
def d():
    for i, item in list(enumerate(n))[::nth]:
       if i % nth == 0:
           item    
def enumerates(sequence, start=0, jump=1):
    n = start
    j = start
    for elem in sequence:
        if j % jump == 0:
            yield n, elem
            n += 1
        j += 1            
def e():
    for i, item in enumerates(n, jump= nth):
        item    
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("a()", setup="from __main__ import a")) # 10.556324407152305
    print(timeit.timeit("b()", setup="from __main__ import b")) # 2.7166204783010137
    print(timeit.timeit("c()", setup="from __main__ import c")) # 1.0285353306076601
    print(timeit.timeit("d()", setup="from __main__ import d")) # 8.283859051918608
    print(timeit.timeit("e()", setup="from __main__ import e")) # 14.91601851631981

But if you are really looking for perfomance you should read @Martijn Pieters answer.

like image 176
Ender Look Avatar answered Oct 31 '25 11:10

Ender Look



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!