Please understand, I searched for this and it already has an answer. However I'm looking for a different way to get this result. This could potentially be flagged as a duplicate although I think there is a cleaner answer for this possibly using itertools (most likely groupby
).
Say I have a list data
. And I want 3 values at a time assume the list is number of valuesⁿ long as to rule out improper amount of values at the end.
data = [1, 2, 3, 4, 5, 6,...]
Here's how I'd like to iterate through the list (this code wouldn't work obviously):
for a, b, c in data:
#perform operations
pass
Now with the code above I'd like a, b, c
to be 1, 2, 3
then 4, 5, 6
respectively in each iteration.
I'm sure there's a cleaner approach out there than the one in the answer I linked to.
For the lazy people that don't want to click on a link to see the approach I'm referring to, here it is:
You can use slices if you want to iterate through a list by pairs of successive elements:
>>>myList = [4, 5, 7, 23, 45, 65, 3445, 234] >>>for x,y in (myList[i:i+2] for i in range(0,len(myList),2)): print(x,y) 4 5 7 23 45 65 3445 234