Table of Contents
Introduction
In this section, we have a task to extract all the python keyword in the given list and print the result. The keywords are the special reserved words with special meaning which cannot be used as identifiers (variables, function name etc.)
Program
import keyword input_list = ["The good thing", "about science is that", "it's true whether", "or not you believe in it."] # Using iskeyword() with loop output_list = [] for sub_string in input_list: for word_split in sub_string.split(): # check for keyword if keyword.iskeyword(word_split): output_list.append(word_split) print("Using loop", str(output_list)) # Using list comprehension output_list1 = [] output_list1 = [i for sub_string in input_list for i in sub_string.split() if keyword.iskeyword(i)] print("Using list comprehension: ",str(output_list1))
Output
Explanation
In the above python code, we have used loop and list comprehension. In both the ways one thing in common, the use of iskeyword() and split(). The split() will convert the string to words and each word is checked whether it is python keyword or not with the help of in-built function iskyeword(). If the word is found to be keyword, it is appended to the output_list*(for both ways) and printed on the screen.
0 Comments