Python | Triplet iteration in List
Last Updated :
22 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
Similar Reads
Python - Pair iteration in list Pair iteration involves accessing consecutive or specific pairs of elements from a list. It is a common task particularly in scenarios such as comparing neighboring elements, creating tuple pairs, or analyzing sequential data. Python provides several ways to iterate through pairs efficiently ranging
2 min read
Add items to List While Iterating - Python Python has many ways to append to a list while iterating. List comprehension is a compact and efficient way to append elements while iterating. We can use it to build a new list from an existing one or generate new values based on a condition.Pythona = [1, 2, 3] a += [i + 4 for i in range(3)] print(
2 min read
How to Modify a List While Iterating in Python Modifying a list while iterating can be tricky but there are several ways to do it safely. One simple way to modify a list while iterating is by using a for loop with the index of each item. This allows us to change specific items at certain positions.Pythona = [1, 2, 3, 4] for i in range(len(a)): i
2 min read
How to Iterate Float List in Python We are given a list of floats and our task is to iterate the list of floats and print the result. In this article, we will see how to iterate the float list in Python. Example: Input: float_list = [3.14, 2.718, 1.618, 0.707]Output: Using for loop:3.142.7181.6180.707Explanation: Here, we are iteratin
3 min read
Index Specific Cyclic Iteration in List - Python When working with lists in Python, there may be cases where we need to iterate over a list starting from a specific index in a cyclic manner. For example, given the list [10, 20, 30, 40, 50], we may want to start iterating from index 2 (i.e., 30) and continue iterating in a cyclic manner. There are
3 min read
Python | Find all triplets in a list with given sum Given a list of integers, write a Python program to find all triplets that sum up to given integer 'k'. Examples: Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10 Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] Input : [12, 3, 6, 1, 6, 9], k = 24 Output : [(12, 6, 6), (12, 9, 3)] Approach #1 :
4 min read