
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to print strings based on the list of prefix
When it is required to print strings based on the list of prefix elements, a list comprehension, the ‘any’ operator and the ‘startswith’ method are used.
Example
Below is a demonstration of the same
my_list = ["streek", "greet", "meet", "leeks", "mean"] print("The list is : ") print(my_list) prefix_list = ["st", "ge", "me", "re"] print("The prefix list is : ") print(prefix_list) my_result = [element for element in my_list if any(element.startswith(ele) for ele in prefix_list)] print("The result is :") print(my_result)
Output
The list is : ['streek', 'greet', 'meet', 'leeks', 'mean'] The prefix list is : ['st', 'ge', 'me', 're'] The result is : ['streek', 'meet', 'mean']
Explanation
- A list of strings is defined and is displayed on the console.
- A list of strings is defined as ‘prefix_list’ and is displayed on the console.
- A list comprehension is used to iterate over the elements and check if an element in the list starts with any of the strings provided in the prefix list.
- If yes, the element is stored in a list.
- This is assigned to a variable.
- This is displayed as output on the console.
- Related Articles
- Program to find longest common prefix from list of strings in Python
- Python – Split Strings on Prefix Occurrence
- Program to perform prefix compression from two strings in Python
- Program to arrange linked list nodes based on the value k in Python
- Python Program to replace elements of a list based on the comparison with a number
- Python - Prefix sum list
- Python – Substitute prefix part of List
- Python program to print all sublists of a list.
- Python program to convert a list to a set based on a common element
- Python program – All occurrences of Substring from the list of strings
- Python program to print duplicates from a list of integers?
- C program to print Excel column titles based on given column number
- Python program to Sort a List of Strings by the Number of Unique Characters
- Python program to convert a list of strings with a delimiter to a list of tuple
- Python Program to Print Middle most Node of a Linked List

Advertisements