search
HomeBackend DevelopmentPython TutorialHow to filter list elements starting with a given prefix using Python?

How to filter list elements starting with a given prefix using Python?

The word prefix is ​​defined by the beginning of a word or letter. In this article, we will learn how to filter list elements starting with a given prefix using Python using Python built-in functions like startswith(), filter(), lambda, and len().

Let us take an example to understand this problem−

Let’s take an example to understand this:
Given element list, My_list = [“Amelia”,  “Kinshuk”,  “Rosy”,  “Aman”]
Keyword to be searched, Prefix = “Am”
Final result = [“Amelia”, “Aman”]

grammar

The following syntax is used in all examples -

startswith()

This is a built-in method in Python that returns true if the given condition is met and the string starts with a specific value.

filter()

The filter() method is applied when we need to filter items based on specific conditions. Simply put, it allows the user to iterate over those elements that satisfy a condition.

lambda

This lambda function in Python is called an anonymous function. It can be used when a function object is required.

len()

This is a built-in method in Python that returns the length of the item in the object.

Use list comprehension

This program uses a list comprehension with a method called startswith() to filter the prefixed elements in the list.

The Chinese translation of

Example

is:

Example

In the following example, we will use a list comprehension in the return statement of a function named prefix_list_element_filter() which will iterate over the list values ​​using a for loop and startswith ()Check prefix. The combination of a for loop and an if statement in the same position is called a list comprehension. Then create the list in the variable my_list. Continuing with the setup of the calling function, pass the parameters my_list (stored list value) and Am (prefix) to filter list elements that start with the given prefix. Finally, we use the variable filter_list to print the results.

def prefix_list_element_filter(lst, prefix):
   return [item for item in lst if item.startswith(prefix)]

# Create the list
my_list = ["Amar", "Bunny", "Aman", "Ganesh", "Rajendra"]
filter_list = prefix_list_element_filter(my_list, "Am")
print("The given element start with prefix:", filter_list)

Output

 The given element start with prefix: ['Amar', 'Aman']

Use for loop

The program uses a for loop to iterate over the given list and checks the prefix using startswith(). It will then use an empty list to store the filtered prefix elements by using a built-in method called append().

The Chinese translation of

Example

is:

Example

In the following example, we first start the program by defining a function using the def keyword, which accepts two parameters - lst (for receiving list values) and prefix (for receiving prefix keywords). Next, it will iterate over the list using a for loop and then set the prefix using the startswith() method, which accepts the parameter prefix value received by the function. The filtered list elements are then added to the variable filtered_list using a method called append() and the result is returned. Now create the list in variable fruit_list. Then use the call function to pass the list value and prefix parameters into the variable filter_list. Finally, the results are printed using a variable named filter_list.

def prefix_list_element_filter(lst, prefix):
   filtered_list = []
   for item in lst:
      if item.startswith(prefix):
         filtered_list.append(item)
   return filtered_list

# Create the list
fruit_list = ["apple", "banana", "avocado", "blue berry", "kiwi"]
filter_list = prefix_list_element_filter(fruit_list, "b")
print("The given element start with prefix:\n", filter_list)

Output

 The given element start with prefix:
 ['banana', 'blue berry']

Use Filter() function

The program uses the filter() function to identify specific prefixes and uses the lambda function to set the prefix through a method called startswith(), which can be used to filter specific prefixes.

The Chinese translation of

Example

is:

Example

In the following example, a function starting with the def keyword is used, which accepts two parameters - lst (receives a list value) and prefix (receives a specific keyword search), this function will filter the list of items based on whether they start with a given prefix. This function returns a prefixed result. Then create a list to store the string values ​​in variable course_list. Next, use a function call to pass the values ​​- pass course_list and "bc" in the variables filter_list. Now use the print function setting the variable name filter_list to get the results.

def prefix_list_element_filter(lst, prefix):
   return list(filter(lambda item: item.startswith(prefix), lst))

# Create the list
course_list = ["dca", "bca", "bcom", "MCA", "pgdca"]
filter_list = prefix_list_element_filter(course_list, "bc")
print("The given element start with prefix:\n", filter_list)
Output
 The given element start with prefix:
 ['bca', 'bcom']
Using list comprehensions with conditional expressions This program uses a function that returns list compression by setting some conditional expressions that can be used to filter list elements that start with a given prefix. The Chinese translation of Example

is:

Example

In the following example, start using the function

filter_list_elements_prefix()

, which accepts two parameters -

lst

(to store the list) and

prefix

(in the function receive a specific prefix during the call). This function returns a new list by using a list comprehension, i.e. the expression item[:len(prefix)] slices the length of each item in lst from the beginning to the prefix and compares it with the prefix. If they are equal, include the item in the new list. Next, create a list to store some string values ​​in the variable

my_list

. Then initialize the variable filter_list, which has the same name as the above function, to pass the values ​​of the list and prefix. Finally, use the variable filter_list to get the results in the print function.

def filter_list_elements_prefix(lst, prefix):
   return [item for item in lst if item[:len(prefix)] == prefix]

# Create the list
my_list = ["tea", "coffee", "cheese", "teaspoon", "sugar"]
filter_list = filter_list_elements_prefix(my_list, "tea")
print("The given element start with prefix:\n", filter_list)

输出

 The given element start with prefix:
 ['tea', 'teaspoon']

结论

我们讨论了解决问题陈述的各种方法,过滤以给定前缀开头的元素。有一些内置函数,如startswith(),append()和len(),可以用于过滤前缀并根据给定条件返回结果。这个程序涉及到现实生活中的例子,比如一个由多个人名组成的名单,可以通过特定的前缀进行搜索。

The above is the detailed content of How to filter list elements starting with a given prefix using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)