Python | Ways to create triplets from given list
Given a list of words, write a Python program to create triplets from the given list.
Examples :
Input: [‘Geeks’, ‘for’, ‘Geeks’, ‘is’, ‘best’, ‘resource’, ‘for’, ‘study’]
Output:
[[‘Geeks’, ‘for’, ‘Geeks’], [‘for’, ‘Geeks’, ‘is’],
[‘Geeks’, ‘is’, ‘best’], [‘is’, ‘best’, ‘resource’],
[‘best’, ‘resource’, ‘for’], [‘resource’, ‘for’, ‘study’]]
Input: [‘I’, ‘am’, ‘Paras’, ‘Jain’, ‘I’, ‘Study’, ‘From’, ‘GFG’]
Output:
[[‘I’, ‘am’, ‘Paras’], [‘am’, ‘Paras’, ‘Jain’],
[‘Paras’, ‘Jain’, ‘I’], [‘Jain’, ‘I’, ‘Study’],
[‘I’, ‘Study’, ‘From’], [‘Study’, ‘From’, ‘GFG’]]
Let’s see some of the methods to do this task.
Method #1: Using List comprehension
# Python code to create triplets from list of words. # List of word initialization list_of_words = ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo'] # Using list comprehension List = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # printing list print(List) |
[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'], ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]
Method #2: Using Iteration
# Python code to create triplets from list of words. # List of word initialization list_of_words = ['Geeks', 'for', 'Geeks', 'is', 'best', 'resource', 'for', 'study'] # Output list initialization out = [] # Finding length of list length = len(list_of_words) # Using iteration for z in range(0, length-2): # Creating a temp list to add 3 words temp = [] temp.append(list_of_words[z]) temp.append(list_of_words[z + 1]) temp.append(list_of_words[z + 2]) out.append(temp) # printing output print(out) |
[['Geeks', 'for', 'Geeks'], ['for', 'Geeks', 'is'], ['Geeks', 'is', 'best'], ['is', 'best', 'resource'], ['best', 'resource', 'for'], ['resource', 'for', 'study']]
Recommended Posts:
- Python | Ways to create a dictionary of Lists
- Python | Find all triplets in a list with given sum
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Ways to sum list of lists and return sum list
- Python | Ways to Convert a 3D list into a 2D list
- Python | Create list of numbers with given range
- Create a tuple from string and list - Python
- Python program to create a list centered on zero
- How to create a list of object in Python class
- Python | Create a dictionary using list with none values
- Python | Ways to flatten a 2D list
- Python | Ways to rotate a list
- Python | Ways to Spilt the list by some value
- Extending a list in Python (5 different ways)
- Different ways to clear a list in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


