Open In App

Python | Triplet iteration in List

Improve
Improve
Like Article
Like
Save
Share
Report

List iteration is common in programming, but sometimes one requires to print the elements in consecutive triplets. This particular problem is quite common and having a solution to it always turns out to be handy. Lets discuss certain way in which this problem can be solved.

Method #1 : Using list comprehension List comprehension can be used to print the triplets by accessing current, next and next to next element in the list and then printing the same. Care has to be taken while pairing the last elements with the first ones to form a cyclic triplet pairs. 

Python3




# Python3 code to demonstrate
# Triplet iteration in List
# using list comprehension
from itertools import compress
 
# initializing list
test_list = [0, 1, 2, 3, 4, 5]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using list comprehension
# Triplet iteration in List
res = [((i), (i + 1) % len(test_list), (i + 2) % len(test_list))
        for i in range(len(test_list))]
 
# printing result
print ("The triplet list is : " + str(res))


Output

The original list is : [0, 1, 2, 3, 4, 5]
The triplet list is : [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 0), (5, 0, 1)]

Time Complexity: O(n)

Auxiliary space: O(n)

Method#2 : Using zip() function zip function can be used to pair the element of the list provided. We generate the list  whose starting element is next element and next to next element. Take care while generating list while merging the last element to first element to form the cyclic triplet.

Python3




# Python3 code to demonstrate
# Triplet iteration in List
# using list comprehension
import itertools
 
# initializing list
l = [0, 1, 2, 3, 4, 5]
# Printing original list
print("The original list is : " + str(l))
# Generating list for pairing
def gen(l, n):
    k1 = itertools.cycle(l);
    k2 = itertools.dropwhile(lambda x: x!=n, k1)
    k3 = itertools.islice(k2, None, len(l))
    return list(k3)
 
# using zip function
# Triplet iteration in List
ans = []
for i in zip(l, gen(l, 1), gen(l, 2)):
    ans.append(tuple(i))
# printing result
print ("The triplet list is : " + str(ans))


Output

The original list is : [0, 1, 2, 3, 4, 5]
The triplet list is : [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 0), (5, 0, 1)]

Time Complexity: O(n)

Auxiliary space: O(n)

Method#3: Using For loop For loop can be used to print the triplets by accessing current, next and next to next in the list then print the same.  Care has to been taken while pairing the last element with first element when forming cyclic triplet.

Python3




# Python3 code to demonstrate
# Triplet iteration in List
# using list comprehension
 
# initializing list
l = [0, 1, 2, 3, 4, 5]
k = len(l)
# Printing original list
print("The original list is : " + str(l))
 
# using zip function
# Triplet iteration in List
ans = []
for i in range(k):
    x = (l[i], l[(i+1)%k], l[(i+2)%k]);
    ans.append(x)
     
# printing result
print ("The triplet list is : " + str(ans))


Output

The original list is : [0, 1, 2, 3, 4, 5]
The triplet list is : [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 0), (5, 0, 1)]

Time Complexity: O(n)

Auxiliary space: O(n)

Method#4: Using zip() and slicing:

Python3




test_list = [0, 1, 2, 3, 4, 5]
# Using zip() and slicing
result = list(zip(test_list, test_list[1:] + test_list[:1], test_list[2:] + test_list[:2]))
print(result)
#This code is contributed by Jyothi pinjala.


Output

[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 0), (5, 0, 1)]

Time Complexity: O(n)

Auxiliary space: O(n)

Method #5: Using recursion

Here’s a solution using recursion in Python:

Python3




def get_triplets_recursive(lst, triplet_lst, index):
    """
    A recursive function that takes the original list, a list to store the triplets and an index
    and appends the triplets to the triplet list.
    """
    # Base case: when the index has reached the end of the list, return
    if index == len(lst):
        return
     
    # Append the current triplet to the triplet list
    triplet_lst.append((lst[index], lst[(index + 1) % len(lst)], lst[(index + 2) % len(lst)]))
     
    # Recursively call the function with the next index
    get_triplets_recursive(lst, triplet_lst, index + 1)
 
def get_triplets(lst):
    """
    A function that takes the original list and returns the list of triplets.
    """
    # Initialize an empty list to store the triplets
    triplet_lst = []
     
    # Call the recursive function with the original list, the empty list of triplets and the starting index 0
    get_triplets_recursive(lst, triplet_lst, 0)
     
    # Return the list of triplets
    return triplet_lst
 
# Example usage
original_list = [0, 1, 2, 3, 4, 5]
triplet_list = get_triplets(original_list)
print(triplet_list)
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 0), (5, 0, 1)]

Time complexity: O(n)

Auxiliary Space: O(n)

Method 6 : using the itertools module

step by step:

  • Import the itertools module.
  • Initialize the list.
  • Use the itertools.cycle() function to cycle through the list.
  • Use the itertools.islice() function to slice the list into triplets.
  • Convert the sliced triplets into a list.
  • Print the resulting list of triplets.

Python3




# Python code to demonstrate
# Triplet iteration in List
# using itertools module
 
# import itertools module
import itertools
 
# initializing list
l = [0, 1, 2, 3, 4, 5]
 
# Printing original list
print("The original list is : " + str(l))
 
# using itertools.cycle() and itertools.islice() functions
# Triplet iteration in List
ans = [list(itertools.islice(itertools.cycle(l), i, i+3)) for i in range(len(l))]
 
# printing result
print ("The triplet list is : " + str(ans))


Output

The original list is : [0, 1, 2, 3, 4, 5]
The triplet list is : [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0], [5, 0, 1]]

Time complexity: O(n), where n is the length of the list.

Auxiliary space: O(n), where n is the length of the list.



Last Updated : 22 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads