- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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.
Advertisements