Python | Check if suffix matches with any string in given list
Last Updated : 02 May, 2023
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
lst = [ "Paras" , "Geeksforgeeks" , "Game" ] Output = any ( 'Geek' in x for x in lst) 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
lst = [ "Paras" , "Geeksforgeeks" , "Game" ] Output = len ( list ( filter ( lambda x: "Jai" in x, lst))) ! = 0 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
res = False lst = [ "Paras" , "Geeksforgeeks" , "Game" ] suffix = "Geeks" for i in lst: if (i.find(suffix) ! = - 1 ): res = True 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
lst = [ "Paras" , "Geeksforgeeks" , "Game" ] suffix = "Geeks" result = False for i in lst: try : idx = i.index(suffix) result = True break except ValueError: continue print ( "Initial List is:" , lst) print (result) |
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
lst = [ "Paras" , "Geeksforgeeks" , "Game" ] suffix = "geeks" result = [s.lower().endswith(suffix.lower()) for s in lst] result = any (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#6: Using regular expressions (regex)
Python3
import re lst = [ "Paras" , "Geeksforgeeks" , "Game" ] suffix = "geeks" result = any (re.search(r ".*" + suffix.lower() + "$" , s.lower()) for s in lst) 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:
- 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.
- Check for the base case where the input list is empty. If the list is empty, return False.
- 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.
- If the first element in the list ends with the suffix, return True.
- 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).
- 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) |
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 lst = [ "Paras" , "Geeksforgeeks" , "Game" ] suffix = "geeks" arr = np.array(lst) result = np. any (np.char.endswith(arr, suffix)) 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.
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