Python – Get Every Element from a String List except for a specified letter

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 04-Sep-2021 11:15:46
Advertisements