Open In App

Generate All Possible Permutations of Words ina Sentence

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to generate all possible permutations of words in a given sentence. For example, if the input is "sky is blue", the output should include permutations like "sky is blue", "sky blue is", "is sky blue" and so on.

Using itertools.permutations()

permutations() function from the itertools module generates all possible arrangements of words in the sentence.

Python
from itertools import permutations

s = "sky is blue"
words = s.split()

for perm in permutations(words):
    print(" ".join(perm))

Output
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky

Explanation:

  • s.split() splits the sentence into words.
  • permutations(words) generates all possible word arrangements.
  • " ".join(perm) joins each permutation into a sentence before printing.

Using Recursion

We can generate all permutations of words using recursion by swapping elements.

Python
def permute(words, l, r):
    if l == r:
        print(" ".join(words))
    else:
        for i in range(l, r + 1):
            words[l], words[i] = words[i], words[l]  # Swap
            permute(words, l + 1, r)
            words[l], words[i] = words[i], words[l]  # Backtrack

s = "sky is blue"
words = s.split()
permute(words, 0, len(words) - 1)

Output
sky is blue
sky blue is
is sky blue
is blue sky
blue is sky
blue sky is

Explanation:

  • function permute(words, l, r) swaps words recursively to generate all possible permutations.
  • When l == r, it prints the sentence, meaning a complete permutation has been formed.
  • Swapping and backtracking ensure all arrangements are explored without modifying the original list.

Using itertools.permutations() with List Comprehension

We can simplify the permutation generation using a one-liner with list comprehension.

Python
from itertools import permutations

s = "sky is blue"
words = s.split()

res = [" ".join(p) for p in permutations(words)]
print("\n".join(res))

Output
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky

Explanation:

  • permutations(words) generates all word permutations.
  • [" ".join(p) for p in permutations(words)] creates a list of permuted sentences.
  • "\n".join(res) prints each permutation on a new line.

Similar Reads