

- 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 – Get Every Element from a String List except for a specified letter
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.
- Related Questions & Answers
- Python – Remove Tuples from a List having every element as None
- Python Program to remove a specific digit from every element of the list
- MySQL query to get a substring from a string except the last three characters?
- Remove Tuples from the List having every element as None in Python
- Removing the specified element from the List in C#
- Change every letter to next letter - JavaScript
- Python Program To Get Minimum Element For String Construction
- Python Get a list as input from user
- Get unique values from a list in Python
- Style every element that is not the specified element with CSS
- Get first three letters from every string in C#
- Remove the specified element from a HashSet in C#
- How to check whether a List contains a specified element in C#
- Insert a specified element in a specified position in JavaScript?
- C# Program to get the smallest and largest element from a list
Advertisements