Check if the first and the last letter of the string are the same(Python)

Question:

I have a list of strings and I wanted to count how many words are having same first and last letter:


strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0 

for word in strings:
   if word[0] == word[-1]:
       count += 1

print(count)

It gives me a result 0, when its supposed to give 3, what am i doing wrong?

Answers:

You could use .lower because "a" is not equal to "A".

strings = ["Ana", "Alice", "Bob", "Alex", "Alexandra"]

count = 0

for word in strings:
    if word[0].lower() == word[-1].lower():
        count += 1

print(count)
Answered By: Teddy

And if you’re into list comprehensions, this could also be written as:

sum(word[0].lower() == word[-1].lower() for word in strings)

True and False become 1 and 0 when summed.

Answered By: Frank Yellin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.