Loop through a list with itertools.islice

Question:

I’m trying to check the first 5 elements in a list, see if two or more are greater or equal to 5, and then check the next 5 elements with the same process.

I have this working by creating a new list and appending the next 5 elements:

from itertools import islice

myList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4]
print(sum(i>5 for i in islice(myList, 5)) >= 2)
newlist = myList[5:]
print(sum(i>5 for i in islice(newlist, 5)) >= 2)

Is there a way to loop through the original list, checking 5 elements at a time without creating a new list?

Asked By: Martaer

||

Answers:

You can just use a range with step 5

myList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4]

for i in range(0, len(myList), 5):
    if sum(v > 5 for v in myList[i:i+5]) > 1:
        print(f'Chunk {i}->{i+5} has two or more values greater than 5')

Output:

Chunk 5->10 has two or more values greater than 5
Answered By: OldBill
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.