How to iterate elements by 5 : Python

I have a list that is about 90 in length, I would like to iterate so that 5 objects at each iteration have different values, at each integration I do a print to see the elements, like this:

L= ["a","b","c","d","e","f","g","h","i","j"]
loop....
   print(first,second,third,fourth,fifth)
>>> "a" , "b" , "c" , "d" , "e" -> first iteration
>>> "f","g","h","i","j" -> second iteration

how can I proceed ?

>Solution :

If you know that length of the list a product of 5, then you can use the following

for index in range(0,len(L),5):
    first=L[index]
    second=L[index+1]
    third=L[index+2]
    fourth=L[index+3]
    fifth=L[index+4]
    print(first,second,third,fourth,fifth)

If it isn’t, and you want the rest fo to be printed too, then you can use the following code:

for index in range(0,len(L),5):
    if index+5>len(L):
        print(" ".join(L[index:]))
    else:
        print(" ".join(L[index:index+5]))

Leave a Reply