Reputation: 4981
I'm using Python3. I want to get 4 items from mylist
to populate list2 and print my list2 every 4 loops. And I need to print the rest even if there are just 1, 2 or 3 items at the end.
I want to do this with mod %
:
mylist = [1, 2, 3, 4, 5]
list2 = []
for count, el in enumerate(mylist):
list2.append(el)
if count % 4 == 0:
print(list2)
list2 = []
Output :
[1]
[2, 3, 4, 5]
But I need the inverse.
I tried to start at 1 enumerate(mylist, 1):
but the output is [1, 2, 3, 4]
the last is ignored.
The output that I need is :
[1, 2, 3, 4]
[5]
The length of mylist
is totally random. How can I do to get the output that I want ?
Upvotes: 1
Views: 338
Reputation: 7510
Sounds to me you just want to chunk the data into groups of 4. This is done best here:
How do you split a list into evenly sized chunks?
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
for i in chunks(mylist,4):
print(i)
Upvotes: 1
Reputation: 8572
@remcogerlich wrote a good answer for what you're asking for. Although, I'd recommend not using % 4
for what you're achieving (until its some kind of homework from school) and use list slicing instead:
n = 4
for i in range(0, len(mylist), n):
print(mylist[i:i + n])
Python can handle index "overflow" so you can write more high-level code instead of caring about tail size. Take a look at similar old question
Upvotes: 1
Reputation: 31260
You have two problems. One is the start at 0, as you noticed. The second is that you only print if the list has exactly 4 elements, so if there is something left at the end, then there is no print call anymore after the loop that prints those remaining values. Add it at the end:
mylist = [1, 2, 3, 4, 5]
list2 = []
for count, el in enumerate(mylist, 1):
list2.append(el)
if count % 4 == 0:
print(list2)
list2 = []
if list2: print(list2)
Upvotes: 2
Reputation: 22023
count
starts at 0
, and 0%4==0
.
So just use the enumerate as you did and then at the end
if len(list2) != 0
print(list2)
Upvotes: 2