Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads