Table of Contents
grammar
Use list comprehension
Example
Output
Use for loop
Use Filter() function
In the following example, start using the function
(to store the list) and
(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
输出
结论
Home Backend Development Python Tutorial How to filter list elements starting with a given prefix using Python?

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

Aug 20, 2023 am 11:29 AM
python filter prefix

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”]
Copy after login

grammar

The following syntax is used in all examples -

startswith()
Copy after login

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()
Copy after login

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
Copy after login

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

len()
Copy after login

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)
Copy after login

Output

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

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)
Copy after login

Output

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

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)
Copy after login
Output
 The given element start with prefix:
 ['bca', 'bcom']
Copy after login
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)
Copy after login

输出

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

结论

我们讨论了解决问题陈述的各种方法,过滤以给定前缀开头的元素。有一些内置函数,如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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles