Home Ask Login Register

Developers Planet

Your answer is one click away!

user256107 February 2016

python list elements start with and end with same character

Very new and beginner to python, got a small assignment to do this

Suppose that you have a list of strings named samples.
Write a Python loop that goes through the list and counts the number of strings where the string length is 2 or more and the first and last characters of the strings are the same.

Test your code on the following three versions of the list samples:
samples = ['aba', 'xyz', 'aa', 'x', 'bbb']
samples = ['', 'x', 'xy', 'xyx', 'xx']
samples = ['aaa', 'be', 'abc', 'hello']

What i tried did not work it returned nothing for me

samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
 if ( len(elem) >=2 and str.startswith('"') and str.endswith('"')):


Prune February 2016

The quotation marks are not part of the string; they will not match for you. Rather, you want an innermost comparison such as


Note that str is the documentation's way of saying "put your string here". Let's update the program so far:

samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
    if (len(elem) >=2 and elem.endswith(elem[0])):



Post Status

Asked in February 2016
Viewed 2,721 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life