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)
range(len(s))
is not very good way to write Python" not sure where you got that idea, from that question or otherwise. It is perfectly ok Python. What is not advised is to iterate over indices and then get the element within the loop; thenenumerate
is preferred. – jdehesa Feb 27 '18 at 10:46range(len(l))
when you want to iterate the elements of a list (although there may still be cases where it makes sense). But if you only want to iterate through a sequence of numbers, be it up tolen(l)
or any other number, it is the right way to do it (in fact, it is the very purpose ofrange
/xrange
). Imo usingenumerate
in that case and ignoring the list element is unnecessary and, most importantly, slightly less explicit about the fact that you are not using the list element. – jdehesa Feb 27 '18 at 10:58