Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Group Similar Start and End character words
Next article icon

Python | Strings with similar front and rear character

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while programming, we can have a problem in which we need to check for the front and rear characters of each string. We may require to extract the 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 a brute force method by which this task can be performed. In this, iterate each element of a list and check for each string’s front and rear character and increase the counter in case we find a match. 

Python3




# 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 loop
count = 0
for ele in test_list:
    if ele[0] == ele[-1]:
        count = count + 1
 
# printing result
print("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

Time Complexity: O(n), where n is the length of the input list. This is because we’re using loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re using constant additional space.

Method #2: Using sum() + generator expression 

This is a one-liner alternative to perform this task. In this, we perform the task of iteration using generator expression and summation using sum(). 

Python3




# 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 expression
res = sum(1 for ele in test_list if ele[0] == ele[-1])
 
# printing result
print("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

Method #3: Using startswith() and endswith() methods

Python3




# 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 loop
count = 0
for ele in test_list:
    if ele.startswith(ele[0]) == ele.endswith(ele[0]):
        count = count + 1
 
# printing result
print("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 4:  Using list comprehension. 

Approach:

  1. Initialize the list of strings.
  2. Use a list comprehension to create a list of booleans indicating whether each string has similar front and rear elements.
  3. Use the sum() function to count the number of True values in the list.
  4. Print the result.

Python3




# Python3 code to demonstrate working of
# Similar front and rear elements
# Using list comprehension
 
# initialize list
test_list = ['gfg', 'is', 'best', 'treat']
 
# printing original list
print("The original list : " + str(test_list))
 
# Similar front and rear elements
# Using list comprehension
count = sum([ele.startswith(ele[0]) == ele.endswith(ele[0]) for ele in test_list])
 
# printing result
print("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

Time complexity: O(n), where n is the number of elements in the list. 
Auxiliary Space: O(n), because we are creating a list of booleans with n elements.

Method #5 : Using count() method

Approach

  1. Initiate a for loop to traverse list of strings
  2. For each string concatenate first and last character
  3. Check whether occurrence of first character in concatenated string is 2 using count()
  4. If yes increment count by 1 
  5. Display count

Python3




# 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 loop
count = 0
for ele in test_list:
    x=ele[0]+ele[-1]
    if(x.count(ele[0])==2):
        count+=1
 
# printing result
print("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

Time complexity: O(n), where n is the number of elements in the list. 
Auxiliary Space: O(1)



Next Article
Python - Group Similar Start and End character words
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Similar characters Strings comparison
    Given two Strings, separated by delim, check if both contain same characters. Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!' Output : True Explanation : Same characters, just diff. positions. Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!' Output : False Ex
    6 min read
  • Python | Kth index character similar Strings
    Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Let’s discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
    3 min read
  • Python - Sort by Rear Character in Strings List
    Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
    6 min read
  • Python - Group Similar Start and End character words
    Sometimes, while working with Python data, we can have problem in which we need to group all the words on basis of front and end characters. This kind of application is common in domains in which we work with data like web development. Lets discuss certain ways in which this task can be performed. M
    5 min read
  • Python - Right and Left Shift characters in String
    In string manipulation tasks, especially in algorithmic challenges or encoding/decoding scenarios, we sometimes need to rotate (or shift) characters in a string either to the left or right by a certain number of positions. For example, let's take a string s = "geeks" and we need to perform a left an
    4 min read
  • Python | Rear stray character String split
    C/C++ Code # Python3 code to demonstrate working of # Rear stray character String split # Using list comprehension # initializing string test_str = 'gfg, is, best, ' # printing original string print("The original string is : " + test_str) # Rear stray character String split # Using list co
    5 min read
  • Python - Strings with all given List characters
    GIven Strings List and character list, extract all strings, having all characters from character list. Input : test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"], chr_list = [ 'f', 'r', 'e'] Output : ['free', "Geeksforgeeks"] Explanation : Only "free" and "Geeksforgeeks" contains all 'f', 'r' and
    4 min read
  • Python - Filter Tuples with Strings of specific characters
    Given a Tuple List, extract tuples, which have strings made up of certain characters. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb' Output : [('gfg', 'best'), ('fest', 'gfg')] Explanation : All tuples contain characters from char_str. Input : test_list
    5 min read
  • Reverse Alternate Characters in a String - Python
    We have to reverse the alternate characters in a given string. The task is to identify every second character in the string, reverse their order and keep the other characters unchanged. For example, "abcd" needs to be changed to "cbad" and "abcde" needs to be changed to "ebcda" This can be accomplis
    4 min read
  • Python Program to check for almost similar Strings
    Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K. Input : test_str1 = 'aabcdaa', test
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences