Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python range len vs enumerate

I read from range(len(list)) or enumerate(list)? that using range(len(s)) is not very good way to write Python. How one can write for loops in alternative way if we do not need to loop len(s) times but for example len(s)//3 times or len(s)-5 times? Is it possible to convert those loops to use enumerate?

For example, I had a project where I had a list of 3n elements 's[0], s[1],...,s[3n-1]' and I needed to print them in a nx3 table. I wrote the code something like

for i in range(len(s)//3):
    row = str(s[3*i]) + " " + str(s[3*i+1]) + " " + str(s[3*i+2])
    print(row)
like image 406
Jaakko Seppälä Avatar asked Feb 27 '18 10:02

Jaakko Seppälä


2 Answers

If you're iterating over an entire list:

for x in lst:
    print(x)

If you're iterating over an entire list, but you only need the index:

for i, _ in enumerate(lst):
    print(i)

If you're iterating over an entire list, but you don't need the index or the data:

for _ in lst:
    print("hello")

If you're iterating over part of a list:

for x in lst[:-5]:
    print(x)

And so on.

I'm not sure why you want to iterate over part of a list though, that seems strange. I'd be interested to hear your use case, as it could probably be improved.

Looking over the code you've now posted, @Metareven has a good solution - iterating over the list in chunks of the size you want to process.

like image 124
Adam Barnes Avatar answered Oct 06 '22 00:10

Adam Barnes


Your code doesn't look that bad, but if you want to iterate over 3 elements at a time I would make a for loop that increments the i variable by 3 instead of one, like so:

for i in range(0,len(s),3):
  row = str(s[i]) + " " + str(s[i+1]) + " " + str(s[i+2])
  print(row)
like image 36
Metareven Avatar answered Oct 05 '22 23:10

Metareven