3

How can I create iterate group of three from a iterate object? For creating a pair of iteration function I can do something like from itertools import tee

def func(iterate):
    i, j = tee(iterate)
    next(j, None)
    return zip(i, j)

l = [1,2,3,4,5]
for a, b in func(l):
    print(a, b)
> 1, 2
> 2, 3
> 3, 4
> 4, 5

2 Answers 2

1

You can expand on what you already did for groups of two, but with one more variable for the third item:

def func(iterate):
    i, j, k = tee(iterate, 3)
    next(j, None)
    next(k, None)
    next(k, None)
    return zip(i, j, k)

l = [1,2,3,4,5]
for a, b, c in func(l):
    print(a, b, c)

This outputs:

1 2 3
2 3 4
3 4 5

Note that your sample code in the question is incorrect as it is missing a call to zip in the returning value from func.

Sign up to request clarification or add additional context in comments.

Comments

0

Use zip():

l = [1,2,3,4,5]

for a, b, c in zip(l, l[1:], l[2:]):
    print(a, b, c)

# 1 2 3
# 2 3 4
# 3 4 5

You can also create groups of two with this method:

l = [1,2,3,4,5]

for a, b in zip(l, l[1:]):
    print(a, b)

# 1 2
# 2 3
# 3 4
# 4 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.