
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ways to Create Triplets from Given List in Python
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']]
Advertisements