Home > OS >  How to iterate elements by 5 : Python
How to iterate elements by 5 : Python

Time:11-05

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 ?

CodePudding user response:

If you don't sure about the length of the list you can use itertools.cycle then use islice like below:

import math
from itertools import cycle , islice
L = ["a","b","c","d","e","f","g","h"]
i = cycle(L)
slc = 5
for _ in range(math.ceil(len(L)/slc)):
    print(list(islice(i,slc)))

Output:

['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'a', 'b']

If you sure about the length you can use itertools.islice and get what you want like below:

from itertools import islice
L = ["a","b","c","d","e","f","g","h","i","j"]
i = iter(L)
slc = 5
for _ in range(len(L)//slc):
    print(list(islice(i,slc)))

Output:

['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'i', 'j']

CodePudding user response:

L = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
for i in range(0, len(L), 5):
    print(L[i:i   5])
['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'i', 'j']

CodePudding user response:

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]))
  • Related