Python | Ways to create triplets from given list
Last Updated :
14 Jan, 2025
To create triplets from a given list, we aim to group consecutive elements into sublists of three. This process involves iterating through the list and extracting segments of three adjacent elements, resulting in a new list where each item is a triplet.
Using list comprehension
List Comprehension in Python provides a clean and efficient approach to achieve this. It iterates through the list, slicing the elements into smaller groups of three, and stores these sublists in the result list.
Python
li = ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo']
res = [li[i:i + 3] for i in range(len(li) - 2)]
print(res)
Output[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'], ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]
Explanation:
List comprehension
: This iterates through the list li
and slices it into sublists of size 3, starting from index i
.range(len(li) - 2):
This
ensures that the loop runs enough times to create triplets without going out of bounds when slicing the list.li[i:i + 3]:
This
creates a sublist starting at index i
and ending at index i + 3
.
Using tee()
tee()
function from the itertools
module in Python allows the creation of multiple independent iterators from a single iterable, making it possible to generate triplets without re-iterating over the list. By using tee()
with the islice()
function,we can create three iterators that simulate a sliding window of triplets.
Python
import itertools
li= ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo']
# Create 3 iterators
it1, it2, it3 = itertools.tee(li, 3)
# Advance iterators
it2 = itertools.islice(it2, 1, None)
it3 = itertools.islice(it3, 2, None)
# Create triplets
res = list(zip(it1, it2, it3))
print(res)
Output[('I', 'am', 'Paras'), ('am', 'Paras', 'Jain'), ('Paras', 'Jain', 'I'), ('Jain', 'I', 'Study'), ('I', 'Study', 'DS'), ('Study', 'DS', 'Algo')]
Explanation:
tee()
: This creates 3 independent iterators from the original list li
.islice()
:it1
starts from the first element, it2
starts from the second and it3
starts from the third effectively simulating a sliding window.zip()
: This combines the three iterators to form triplets, iterating through the list once.
Using loop
simple loop is a straightforward approach to manually collect triplets from a list. This method iterates through the list and slices it to create triplets, providing more control over the process.
Python
li= ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo']
res = [] # An empty list res is initialized
for i in range(len(li) - 2):
res.append(li[i:i + 3])
print(res)
Output[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'], ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]
Explanation:
- len(li) - 2: As we need 3 elements to form each triplet that's why we need to stop loop before reaching the last 2 elements to avoid slicing beyond the list length.
- li[i:i+3]: In each iteration this slices 3 consecutive elements starting from index i.
- res.append(...): Each triplet formed by the slice is appended to the res list .
Using deque
deque
from collections
module can be used to create triplets by maintaining a sliding window. This method uses a deque to store the last three elements. When the deque size reaches 3 it appends the current window to the list of triplets.
Python
from collections import deque
li = ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo']
window = deque(maxlen=3)
# An empty list res is initialized
res = []
for word in li:
window.append(word)
if len(window) == 3:
res.append(list(window))
print(res)
Output[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'], ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]
Explanation:
deque(maxlen=3)
: This creates a deque that holds up to 3 elements, automatically discarding the oldest when a new element is added.for word in li
: This Loops through each word in li
and adds it to the window
deque.window.append(word)
: This adds the word to the deque, removing the oldest if it exceeds 3 elements.if len(window) == 3
: This checks if the deque has 3 elements before forming a triplet.res.append(list(window))
: This converts the deque to a list and appends it to res
as a triplet.
Similar Reads
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
How to Yield Values from List in Python In Python, we often deal with large lists where processing all elements at once might be inefficient in terms of memory usage. The yield keyword allows us to create iterators that yield values one at a time, instead of storing them all in memory. In this article, we will explore different methods to
3 min read
Python - Create list of tuples using for loop In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
2 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
Python | Triplet iteration in List 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 co
6 min read