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

 Live Demo

# 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']]

Updated on: 06-Aug-2020

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements