
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Get Every Element from a String List Except for a Specified Letter in Python
When it is required to get every element from a list of strings except a specified letter, a list comprehension and the ‘append’ method is used.
Below is a demonstration of the same −
Example
my_list = ["hi", "is", "great", "pyn", "pyt"] print("The list is :") print(my_list) my_key = 'n' print("The value for key is ") print(my_key) my_result = [] for sub in my_list: my_result.append(''.join([element for element in sub if element == my_key])) print("The result is :") print(my_result)
Output
The list is : ['hi', 'is', 'great', 'pyn', 'pyt'] The value for key is n The result is : ['', '', '', 'n', '']
Explanation
A list of strings is defined and is displayed on the console.
The value for a key is defined and displayed on the console.
An empty list is defined.
The original list is iterated over using list comprehension, and checked to see if an element is equal to the key.
If so, it is appended to the empty list.
This list is displayed as the output on the console.
Advertisements