Python Program to Extract Strings with at least given number of characters from other list

When you need to extract strings that contain at least a specified number of characters from a given character list, list comprehension provides an efficient solution. This technique counts how many target characters appear in each string and filters based on a minimum threshold.

Example

Below is a demonstration of extracting strings with at least 2 characters from a specified character list ?

my_list = ["Python", "is", "fun", "to", "learn"]

print("The list is :")
print(my_list)

my_char_list = ['e', 't', 's', 'm', 'n']

my_key = 2
print("The value of key is")
print(my_key)

my_result = [element for element in my_list if sum(ch in my_char_list for ch in element) >= my_key]

print("The resultant list is :")
print(my_result)

Output

The list is :
['Python', 'is', 'fun', 'to', 'learn']
The value of key is
2
The resultant list is :
['Python', 'learn']

How It Works

The list comprehension uses a nested generator expression to count matching characters:

  • ch in my_char_list for ch in element generates True/False for each character

  • sum() counts the True values (Python treats True as 1, False as 0)

  • Only strings with count >= my_key are included in the result

Alternative Approach Using Filter

You can also use the filter() function for the same result ?

strings = ["Python", "is", "fun", "to", "learn"]
target_chars = ['e', 't', 's', 'm', 'n']
min_count = 2

def has_min_chars(word):
    return sum(char in target_chars for char in word) >= min_count

result = list(filter(has_min_chars, strings))
print("Filtered strings:", result)
Filtered strings: ['Python', 'learn']

Conclusion

List comprehension with sum() provides a concise way to filter strings based on character count. This approach is both readable and efficient for extracting strings that meet specific character requirements.

Updated on: 2026-03-26T02:17:26+05:30

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements