Create a list of words with their characters sorted


This Python code takes a list of words and creates a new list called sorted_chars using a list comprehension. The new list contains the same words as the original list, but with their characters sorted in alphabetical order. Here's how the code works:

  • words = ["apple", "banana", "cherry"]: This line initializes a variable named words and assigns it a list containing three words.
  • sorted_chars = [''.join(sorted(word)) for word in words]: This line of code initializes a variable named sorted_chars and assigns it the result of a list comprehension.
    • for word in words: This part sets up a loop that iterates through each word word in the words list.
    • sorted(word): For each word in the list, this expression sorts its characters in alphabetical order using the sorted() function. The sorted() function returns a list of sorted characters.
    • ''.join(sorted(word)): This part joins the sorted characters back together into a single string by using the join() method. The result is a word with its characters sorted alphabetically.
    • [''.join(sorted(word)) for word in words]: This is the list comprehension itself. It iterates through the words in the words list, sorts the characters of each word, and includes the sorted words in the new list.
  • print(words): This line of code prints the original words list to the console.
  • print(sorted_chars): This line of code prints the sorted_chars list to the console.

Source Code

words = ["apple", "banana", "cherry"]
sorted_chars = [''.join(sorted(word)) for word in words]
print(words)
print(sorted_chars)

Output

['apple', 'banana', 'cherry']
['aelpp', 'aaabnn', 'cehrry']

Example Programs