Python program to extract Keywords from a list


When it is required to extract keywords from a list, a simple iteration and the ‘iskeyword’ method is used.

Example

Below is a demonstration of the same −

import keyword

my_list = ["python", 'is', 'fun', 'to', 'learn']

print("The list is :")
print(my_list)

my_result = []
for element in my_list:
   for word in element.split():

      if keyword.iskeyword(word):
         my_result.append(word)

print("The result is :")
print(my_result)

Output

The list is :
['python', 'is', 'fun', 'to', 'learn']
The result is :
['is']

Explanation

  • A list of strings is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and every element is split based on spaces.

  • The ‘iskeyword’ method is used to check if any of the elements in the list are a keyword in the language.

  • If yes, it is appended to the empty list.

  • This list is displayed on the console as the output.

Updated on: 08-Sep-2021

637 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements