Python | Remove Reduntant Substrings from Strings List
Given list of Strings, task is to remove all the strings, which are substrings of other Strings.
Input : test_list = [“Gfg”, “Gfg is best”, “Geeks”, “for”, “Gfg is for Geeks”]
Output : [‘Gfg is best’, ‘Gfg is for Geeks’]
Explanation : “Gfg”, “for” and “Geeks” are present as substrings in other strings.
Input : test_list = [“Gfg”, “Geeks”, “for”, “Gfg is for Geeks”]
Output : [‘Gfg is for Geeks’]
Explanation : “Gfg”, “for” and “Geeks” are present as substrings in other strings.
Method #1 : Using enumerate() + join() + sort()
The combination of above functions can be used to solve this problem. In this, first the sorting is performed on length parameter, and current word is checked with other words, if it occurs as substring, if yes, its excluded from filtered result.
Python3
# Python3 code to demonstrate working of# Remove Reduntant Substrings from Strings List# Using enumerate() + join() + sort()# initializing listtest_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]# printing original listprint("The original list : " + str(test_list))# using loop to iterate for each stringtest_list.sort(key = len)res = []for idx, val in enumerate(test_list): # concatenating all next values and checking for existence if val not in ', '.join(test_list[idx + 1:]): res.append(val)# printing resultprint("The filtered list : " + str(res)) |
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] The filtered list : ['Gfg is best', 'Gfg is for Geeks']
Method #2 : Using list comprehension + join() + enumerate()
The combination of above functions can be used to solve this problem. In this, we perform task in similar way as above just the difference being in more compact way in list comprehension.
Python3
# Python3 code to demonstrate working of# Remove Reduntant Substrings from Strings List# Using list comprehension + join() + enumerate()# initializing listtest_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]# printing original listprint("The original list : " + str(test_list))# using list comprehension to iterate for each string# and perform join in one linertest_list.sort(key = len)res = [val for idx, val in enumerate(test_list) if val not in ', '.join(test_list[idx + 1:])]# printing resultprint("The filtered list : " + str(res)) |
The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] The filtered list : ['Gfg is best', 'Gfg is for Geeks']



