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 - Strings with all given List characters
Next article icon

Python | Check if suffix matches with any string in given list

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of strings, the task is to check whether the suffix matches any string in the given list.

Examples: 

Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output:  True
Input: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output:  False

Let’s discuss a few methods to do the task.

Method #1: Using any() The most concise and readable way to check whether a suffix exists in a list of strings is to use any() method.

Python3




# Python code to check whether
# suffix exists in list of strings.
 
# Input list initialization
lst = ["Paras", "Geeksforgeeks", "Game"]
 
# using any to find suffix
Output = any('Geek' in x for x in lst)
 
# Printing output
print("Initial List is :", lst)
print(Output)
 
 
Output
Initial List is : ['Paras', 'Geeksforgeeks', 'Game'] True

Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in list 

Method #2: Using filter() and lambda This is yet another way to perform this particular task using lambda(). 

Python3




# Python code to check whether
# suffix exists in list of strings.
 
# Input list initialization
lst = ["Paras", "Geeksforgeeks", "Game"]
 
# Using filter and lambda
Output = len(list(filter(lambda x: "Jai" in x, lst))) != 0
 
# Printing output
print("Initial List is : ", lst)
print(Output)
 
 
Output
Initial List is :  ['Paras', 'Geeksforgeeks', 'Game'] False

Method #3 :Using find() method.The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found.

Python3




# Python code to check whether
# suffix exists in list of strings.
 
res = False
# Input list initialization
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "Geeks"
for i in lst:
    if(i.find(suffix) != -1):
        res = True
 
 
# Printing output
print("Initial List is :", lst)
print(res)
 
 
Output
Initial List is : ['Paras', 'Geeksforgeeks', 'Game'] True

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

Method #4 : Using the index method and a try/except block:

Here is an approach using the index method and a try/except block:

Python3




# initializing list
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "Geeks"
 
result = False
 
# using try/except and index method
for i in lst:
    try:
        idx = i.index(suffix)
        result = True
        break
    except ValueError:
        continue
 
# printing result
print("Initial List is:", lst)
print(result)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
Initial List is: ['Paras', 'Geeksforgeeks', 'Game'] True

This approach uses the index method to find the position of the suffix in each string. This approach is similar to the third method using a loop and find, but it uses the index method instead of find, and it handles the case where the suffix is not found using a try/except block. It is also more concise and readable than using a loop and find.

Time complexity: O(N)
Space complexity: O(1)

Method#5: Using list comprehension

Python3




# Initialize the list and the suffix to search for
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "geeks"
 
# Use a list comprehension to create a list of True/False values indicating
# whether each string in the list ends with the specified suffix
result = [s.lower().endswith(suffix.lower()) for s in lst]
 
# Use the any() function to check if any of the elements in the result list are True
result = any(result)
 
# Print the result
print("Initial List is:", lst)
print(result)
#This code is contributed by Vinay Pinjala.
 
 
Output
Initial List is: ['Paras', 'Geeksforgeeks', 'Game'] True

Time  Complexity: O(n)

Auxiliary Space: O(n)

Method#6: Using regular expressions (regex)

Python3




import re
 
# Initialize the list and the suffix to search for
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "geeks"
 
# Use a generator expression with the re.search function to check if the suffix exists in any of the words in the list
result = any(re.search(r".*" + suffix.lower() + "$", s.lower()) for s in lst)
 
# Print the result
print("Initial List is:", lst)
print(result)
 
 
Output
Initial List is: ['Paras', 'Geeksforgeeks', 'Game'] True

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#7: Using Recursive method.

Algorithm:

  1. Define a function ends_with_suffix(lst, suffix) that takes in a list lst and a suffix suffix, and returns a boolean indicating whether any of the strings in lst end with the specified suffix.
  2. Check for the base case where the input list is empty. If the list is empty, return False.
  3. For the recursive case, check whether the first element in the list ends with the suffix by calling the endswith() string method. The method is called with the lowercase version of the suffix to ensure that the comparison is case-insensitive.
  4. If the first element in the list ends with the suffix, return True.
  5. If the first element in the list does not end with the suffix, recursively call the ends_with_suffix() function on the remaining list (i.e., the sublist starting at index 1).
  6. Return the boolean result of the recursive call.
     

Python3




def ends_with_suffix(lst, suffix):
    if not lst:
        return False
    if lst[0].lower().endswith(suffix.lower()):
        return True
    return ends_with_suffix(lst[1:], suffix)
 
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "geeks"
result = ends_with_suffix(lst, suffix)
print("Initial List is:", lst)
print(result)
#this code contributed by tvsk
 
 
Output
Initial List is: ['Paras', 'Geeksforgeeks', 'Game'] True

The time complexity of this method is O(n), where n is the length of the input list, because it processes each element of the list at most once. The worst-case time complexity occurs when the suffix is not found in the list, in which case the method makes n recursive calls. The best-case time complexity occurs when the suffix is found in the first element of the list, in which case the method makes only one call to endswith().

The space complexity of this method is O(n), because it creates a new stack frame for each recursive call, which requires additional memory on the call stack. However, the maximum depth of the call stack is equal to the length of the input list, so the space complexity is proportional to the size of the input.

Approach using NumPy library:

Note: Install numpy module using command “pip install numpy”

Algorithm:

Convert the given list to a numpy array.
Use np.char.endswith() to check if the suffix exists in any of the strings in the numpy array.
Use np.any() to check if there is any True value in the result of the previous step.
Return the result.

Python3




import numpy as np
 
# initializing list and suffix to search for
lst = ["Paras", "Geeksforgeeks", "Game"]
suffix = "geeks"
 
# Convert list to numpy array
arr = np.array(lst)
 
# Check if suffix exists in any of the strings
result = np.any(np.char.endswith(arr, suffix))
 
# Print the result
print("Initial List is:", lst)
print(result)
 
 

Output:
Initial List is: [‘Paras’, ‘Geeksforgeeks’, ‘Game’]
True

Time complexity: O(n), where n is the length of the list.

Auxiliary Space: O(n), additional space of size n is created for the numpy array.



Next Article
Python - Strings with all given List characters
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Check if string starts with any element in list
    We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem. Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the mos
    3 min read
  • Python | Check if any String is empty in list
    Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combinati
    6 min read
  • Python | Check if string matches regex list
    Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed usi
    4 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
  • Finding Strings with Given Substring in List - Python
    The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a =
    3 min read
  • Python | Check Numeric Suffix in String
    Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
    6 min read
  • Python | Append suffix/prefix to strings in list
    Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + o
    5 min read
  • Python - Check if String contains any Number
    We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
    2 min read
  • Check if any element in list satisfies a condition-Python
    The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
    3 min read
  • Python - Test if Kth character is digit in String
    Given a String, check if Kth index is a digit. Input : test_str = 'geeks9geeks', K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str = 'geeks9geeks', K = 4 Output : False Explanation : 4th idx element is s, not a digit, hence False. Method #1: Using in operat
    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