Python | Strings with similar front and rear character

• Last Updated : 26 Nov, 2019

Sometimes, while programming, we can have a problem in which we need to check for front and rear character of each string. We may require to extract count of all strings with similar front and rear characters. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force method by which this task can be performed. In this, iterate each element of list and check for each string’s front and rear character and increase the counter in case we find a match.

 # Python3 code to demonstrate working of# Similar front and rear elements# Using loop  # initialize list test_list = ['gfg', 'is', 'best', 'treat']  # printing original list print("The original list : " + str(test_list))  # Similar front and rear elements# Using loopcount = 0for ele in test_list:    if ele[0] == ele[-1]:        count = count + 1   # printing resultprint("Total Strings with similar front and rear elements : " + str(count))
Output :
The original list : ['gfg', 'is', 'best', 'treat']
Total Strings with similar front and rear elements : 2

Method #2 : Using sum() + generator expression
This is one liner alternative to perform this task. In this, we perform the task of iteration using generator expression and summation using sum().

 # Python3 code to demonstrate working of# Similar front and rear elements# Using sum() + generator expression  # initialize list test_list = ['gfg', 'is', 'best', 'treat']  # printing original list print("The original list : " + str(test_list))  # Similar front and rear elements# Using sum() + generator expressionres = sum(1 for ele in test_list if ele[0] == ele[-1])  # printing resultprint("Total Strings with similar front and rear elements : " + str(res))
Output :
The original list : ['gfg', 'is', 'best', 'treat']
Total Strings with similar front and rear elements : 2

My Personal Notes arrow_drop_up