Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading