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
from itertools import compress
test_list = [ 0 , 1 , 2 , 3 , 4 , 5 ]
print ( "The original list is : " + str (test_list))
res = [((i), (i + 1 ) % len (test_list), (i + 2 ) % len (test_list))
for i in range ( len (test_list))]
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
import itertools
l = [ 0 , 1 , 2 , 3 , 4 , 5 ]
print ( "The original list is : " + str (l))
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)
ans = []
for i in zip (l, gen(l, 1 ), gen(l, 2 )):
ans.append( tuple (i))
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
l = [ 0 , 1 , 2 , 3 , 4 , 5 ]
k = len (l)
print ( "The original list is : " + str (l))
ans = []
for i in range (k):
x = (l[i], l[(i + 1 ) % k], l[(i + 2 ) % k]);
ans.append(x)
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 ]
result = list ( zip (test_list, test_list[ 1 :] + test_list[: 1 ], test_list[ 2 :] + test_list[: 2 ]))
print (result)
|
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):
if index = = len (lst):
return
triplet_lst.append((lst[index], lst[(index + 1 ) % len (lst)], lst[(index + 2 ) % len (lst)]))
get_triplets_recursive(lst, triplet_lst, index + 1 )
def get_triplets(lst):
triplet_lst = []
get_triplets_recursive(lst, triplet_lst, 0 )
return triplet_lst
original_list = [ 0 , 1 , 2 , 3 , 4 , 5 ]
triplet_list = get_triplets(original_list)
print (triplet_list)
|
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
import itertools
l = [ 0 , 1 , 2 , 3 , 4 , 5 ]
print ( "The original list is : " + str (l))
ans = [ list (itertools.islice(itertools.cycle(l), i, i + 3 )) for i in range ( len (l))]
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.
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
3 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. [GFGTABS] Python a = [1, 2, 3] a += [i + 4 for i in rang
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 | Iterate through value lists dictionary
While working with dictionary, we can have a case in which we need to iterate through the lists, which are in the keys of dictionaries. This kind of problem can occur in web development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension List c
4 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
Python - Repeat Alternate Elements in list
Many times we have this particular use-case in which we need to repeat alternate element of list K times. The problems of making a double clone has been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Letâs discuss certain
7 min read
Create a List of Strings in Python
Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Print a List of Tuples in Python
The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ]. Using print()print() function is the
2 min read
List As Input in Python in Single Line
Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four com
3 min read