Pair and Triplet Iteration in Python List

In this article, we are going to learn about pair and triplet iteration of a list in Python. Sometimes, it happens that we have to consider two or even three elements of a list to solve a problem. Let’s see how to make iterations of those elements one by one with example. We are going to use list comprehension and zip() function to fulfill our purpose of pair and triplet iteration of a list.

Pair iteration of a Python List


We deliberate over two methods for pair iteration. But first, considering a general list for both the examples, let’s initiate it.

l = [1,2,3,4,5,6,7,8]
print("List: ", l)
length = len(l) + 1

The given code snippet gives the following output:

List: [1, 2, 3, 4, 5, 6, 7, 8]

Method 1: Using zip() function


zip() function takes iterables as input and clubs the pair at each index of inputted iterables together. See the Python code below:

#Method 1
double_iter = list(zip(l, l[1:]))
for i in double_iter:
  print (i)

Here, we provide the list l as the first parameter and l[1:], i.e., list l without the first element as the second parameter. It gives us the following output:

(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)

Method 2: Using list comprehension


We club i’th and (i+1)’th elements together until the end of the list. Here’s how to do it. The if statement limits the comprehension to end where the list ends.

#Method 2
double_iter = [[(i), (i+1)%length] for i in l if (i+1)%length >= l[1]]
for i in double_iter:
  print (i)

Output:

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]

Now that we’re done with pair iterations let’s see how to consider triplet iterations.

Triplet iteration of a Python List


As the zip() function uses only pairs of the iterables, it won’t be useful in this case. But list comprehension is still the most effective way for triplet iteration. We club i’th, (i+1)’th, and (i+2)’th elements together until the end of the list. Just like earlier, the if statement limits the comprehension to end where the list ends.

triple_iter = [[(i), (i+1)%length, (i+2)%length] for i in l if (i+2)%length >= l[2]]
for i in triple_iter:
  print (i)

Output:

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]

This is how we use pairs and triplets of a list to iterate. To get familiar with list comprehension and zip() function refer to the following links:

Leave a Reply

Your email address will not be published. Required fields are marked *