- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Ways to create triplets from given list
A list is a collection which is ordered and changeable. In Python lists are written with square brackets. You access the list items by referring to the index number. Negative indexing means beginning from the end, -1 refers to the last item. You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.
Example
# triplets from list of words. # List of word initialization list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # Using list comprehension List = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # printing list print(List) # List of word initialization list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # 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)
Output
[['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']] [['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']]
- Related Articles
- Python - Ways to format elements of given list
- Python - Ways to remove duplicates from list
- Find all triplets in a list with given sum in Python
- Program to check if the given list has Pythagorean Triplets or not in Python
- Python - Ways to rotate a list
- Count ways to form minimum product triplets in C++
- Python – Create dictionary from the list
- Python - Ways to flatten a 2D list
- Python - Ways to initialize list with alphabets
- Python - Ways to merge strings into list
- Python Group Anagrams from given list
- Python Program – Create dictionary from the list
- Program to find folded list from a given linked list in Python
- Create a list of tuples from given list having number and its cube in each tuple using Python
- Create list of numbers with given range in Python

Advertisements