Create a list of first characters from a list of words


This Python code creates a list called first_chars using a list comprehension to extract the first character of each word from the words list. 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."
  • first_chars = [word[0] for word in words]: This line of code initializes a variable named first_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 in the words list.
    • word[0]: For each word in the list, this expression retrieves the first character of the word using indexing [0]. This indexing extracts the character at position 0 in the string, which is the first character.
    • [word[0] for word in words]: This is the list comprehension itself. It iterates through the words in the words list and, for each word, extracts its first character and includes it in the new list.
  • print(words): This line of code prints the original words list to the console.
  • print(first_chars): This line of code prints the first_chars list to the console.

Source Code

words = ["apple", "banana", "cherry"]
first_chars = [word[0] for word in words]
print(words)
print(first_chars)

Output

['apple', 'banana', 'cherry']
['a', 'b', 'c']

Example Programs