Create a list of reversed strings from another list


This Python code takes a list of words, reverses each word in the list, and stores the reversed words in a new list called reversed_words. 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: "apple," "banana," and "cherry."
  • reversed_words = [word[::-1] for word in words]: This line of code initializes a variable named reversed_words and assigns it the result of a list comprehension.
    • for word in words: This part sets up a loop that iterates through each word in the words list.
    • word[::-1]: For each word in the list, this expression uses slicing ([::-1]) to reverse the characters in the word. The [::-1] slice notation reverses the order of characters in a string.
    • [word[::-1] for word in words]: This is the list comprehension itself. It iterates through the words in the words list and, for each word, reverses it and includes the reversed word in the new list.
  • print(words): This line of code prints the original words list to the console.
  • print(reversed_words): This line of code prints the reversed_words list to the console.

Source Code

words = ["apple", "banana", "cherry"]
reversed_words = [word[::-1] for word in words]
print(words)
print(reversed_words)

Output

['apple', 'banana', 'cherry']
['elppa', 'ananab', 'yrrehc']

Example Programs