

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Python Program to replace elements of a list based on the comparison with a number
- Python - Prefix sum list
- Program to arrange linked list nodes based on the value k in Python
- 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
- Deleting the duplicate strings based on the ending characters - JavaScript
- Splitting strings based on multiple separators - JavaScript
- Python program – All occurrences of Substring from the list of strings
- C program to print Excel column titles based on given column number
- Python program to print duplicates from a list of integers?
- Python program to Sort a List of Strings by the Number of Unique Characters
Advertisements