List of words with their first and last letter swapped


This Python code takes a list of words and creates a new list called swapped_words using a list comprehension. In the new list, each word has its first and last letters swapped. Here's how the code works:

  • words = ["apple", "banana", "cherry", "date"]: This line initializes a variable named words and assigns it a list containing four words.
  • swapped_words = [word[-1] + word[1:-1] + word[0] for word in words]: This line of code initializes a variable named swapped_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 word in the words list.
    • word[-1]: This part extracts the last character of the word using negative indexing (-1).
    • word[1:-1]: This part extracts the characters in the word from the second character (index 1) up to, but not including, the last character (index -1).
    • word[0]: This part extracts the first character of the word using indexing (0).
    • word[-1] + word[1:-1] + word[0]: These parts combine the last character, the middle characters, and the first character to form a new word with the first and last letters swapped.
    • [word[-1] + word[1:-1] + word[0] for word in words]: This is the list comprehension itself. It iterates through the words in the words list and creates new words with their first and last letters swapped, including these modified words in the new list.
  • print(words): This line of code prints the original words list to the console.
  • print(swapped_words): This line of code prints the swapped_words list (which contains the modified words) to the console.

Source Code

words = ["apple", "banana", "cherry", "date"]
swapped_words = [word[-1] + word[1:-1] + word[0] for word in words]
print(words)
print(swapped_words)

Output

['apple', 'banana', 'cherry', 'date']
['eppla', 'aananb', 'yherrc', 'eatd']

Example Programs