How To Make An Anagram In Python

Anagrams are a type of word play where you rearrange the letters of a given word to form a new one. This can be a fun exercise to challenge yourself or to create puzzles for others to solve. In this tutorial, we will learn how to make an anagram using Python.

By the end of this tutorial, you will be able to create a simple program that can generate anagrams from a given word.

Step 1: Import the Required Libraries

To begin, we will need to import the following libraries:

  • random: This library is used to shuffle the characters of the given word.
  • sys: This library is used to take command-line arguments.

Step 2: Define a Function to Shuffle the Characters

Next, we will define a function called shuffle_word that takes a single parameter, word, which is the word we want to create an anagram from. The function will randomly shuffle the characters of the word and return the shuffled word.

In this function, we first convert the given word to a list of characters using list(word). Then we use random.shuffle() to shuffle the characters. Finally, we join the shuffled characters using ''.join(word_list) and return the resulting word.

Step 3: Process the Input Word

Now that our function is defined, we can use it to create an anagram of a word given as an input. For this tutorial, we will use command-line arguments to pass the input word to our Python script.

Here, we first check if the user has provided the correct number of command-line arguments (which should be 2, including the script name). If they have not, we display a usage message and exit the program. Otherwise, we take the second command-line argument as our input word and call our shuffle_word function to create an anagram. Finally, we print the original word and the anagram.

The Full Code

Below is the complete code for generating anagrams using Python:

Output Example

After running the script with the word “example” as the input, you might see an output like this:

Please note that the anagram will be different each time you run the script, as the characters are shuffled randomly.


In this tutorial, we have learned how to create a simple Python script that generates an anagram from a given word using the random library. You can now use this script to create anagrams of various words, either for fun or as a learning tool. Happy anagramming!