How to Filter list elements starting with a given Prefix using Python?

Filtering list elements by prefix is a common task in Python programming. We can use several approaches including list comprehension, for loops, filter() function, or string slicing to accomplish this task.

Let's understand with an example ?

# Example: Filter names starting with "Am"
names = ["Amelia", "Kinshuk", "Rosy", "Aman"]
prefix = "Am"
result = [name for name in names if name.startswith(prefix)]
print(result)
['Amelia', 'Aman']

Key Methods Used

startswith() Method

The startswith() method returns True if a string starts with the specified prefix ?

text = "Python programming"
print(text.startswith("Py"))  # True
print(text.startswith("Java"))  # False
True
False

filter() Function

The filter() function creates an iterator from elements that satisfy a condition ?

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
[2, 4]

Method 1: Using List Comprehension

List comprehension provides a concise way to filter elements ?

def filter_by_prefix(items, prefix):
    return [item for item in items if item.startswith(prefix)]

# Filter names starting with "A"
names = ["Alice", "Bob", "Andrew", "Charlie", "Anna"]
filtered = filter_by_prefix(names, "A")
print("Names starting with 'A':", filtered)
Names starting with 'A': ['Alice', 'Andrew', 'Anna']

Method 2: Using For Loop

Traditional approach using a for loop and append() ?

def filter_by_prefix_loop(items, prefix):
    filtered_items = []
    for item in items:
        if item.startswith(prefix):
            filtered_items.append(item)
    return filtered_items

# Filter fruits starting with "ap"
fruits = ["apple", "banana", "apricot", "orange", "grape"]
filtered = filter_by_prefix_loop(fruits, "ap")
print("Fruits starting with 'ap':", filtered)
Fruits starting with 'ap': ['apple', 'apricot']

Method 3: Using filter() with Lambda

Combines filter() function with lambda for functional programming approach ?

def filter_by_prefix_functional(items, prefix):
    return list(filter(lambda item: item.startswith(prefix), items))

# Filter programming languages starting with "P"
languages = ["Python", "Java", "PHP", "JavaScript", "Perl"]
filtered = filter_by_prefix_functional(languages, "P")
print("Languages starting with 'P':", filtered)
Languages starting with 'P': ['Python', 'PHP', 'Perl']

Method 4: Using String Slicing

Alternative approach using string slicing to check prefix ?

def filter_by_prefix_slice(items, prefix):
    return [item for item in items if item[:len(prefix)] == prefix]

# Filter cities starting with "New"
cities = ["New York", "Los Angeles", "New Delhi", "Chicago", "Newark"]
filtered = filter_by_prefix_slice(cities, "New")
print("Cities starting with 'New':", filtered)
Cities starting with 'New': ['New York', 'New Delhi', 'Newark']

Comparison

Method Readability Performance Best For
List Comprehension High Fast Simple filtering tasks
For Loop High Moderate Complex logic needed
filter() + lambda Moderate Fast Functional programming style
String Slicing Moderate Moderate When startswith() unavailable

Conclusion

List comprehension with startswith() is the most Pythonic and efficient approach for filtering list elements by prefix. Use filter() with lambda for functional programming style, and for loops when you need more complex filtering logic.

Updated on: 2026-03-27T08:10:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements