I want to apply a 'for' in a list by fives.
For example;
list = [1,2,3,4,5,6,7,8,9,10]
for a in list:
print(a)
output:
1
2
3
4
5
After these 5 ends, i want it to move to the second 5.
6
7
8
9
10
Thanks.
CodePudding user response:
This is how you can loop through elements 0-4 of your list.
numbers = [1,2,3,4,5,6,7,8,9,10]
for number in numbers[0:5]:
print(number)
I'm not sure what you mean by "After these 5 ends, i want it to move to the second 5." Are you wanting the code to pause then continue counting?
CodePudding user response:
It seems extremely non-idiomatic to write code like this, but perhaps you are looking for something like:
#!/usr/bin/env python
a = [1,2,3,4,5,6,7,8,9,10,11,12]
t = iter(a)
try:
while True:
counter = 1
while i := t.__next__():
print(i)
if counter == 5:
break
counter = 1
print("Finished group")
except StopIteration:
pass
CodePudding user response:
you may be looking for this in collections
chunked(iterable, n) returns an iterable of lists, each of length n (except the last one, which may be shorter);
ichunked(iterable, n) is similar but returns an iterable of iterables instead.