What is keyword.kwlist in Python?
Overview
Python is a high-level programming language that provides functionalities for several operations. The keyword module comes with various methods to manipulate keywords.
The read-only attribute kwlist returns a list of all keywords reserved for the interpreter.
Syntax
kwlist = keyword.kwlist
Return value
This attribute returns a list of all keywords reserved for the interpreter. If any keywords are planned in future versions, they are included too.
Example
#import moduleimport keyword#print kwlistkwlist = keyword.kwlistprint(kwlist)#intialize test stringsstring = 'This attribute returns a list of all keywords reserved for the interpreter. If any keywords are planned in future versions, they are included too.'string_list = string.split()#check if test strings are present in kwlistfor word in string_list:print(word,': ', word in kwlist)
Explanation
- Line 2: We import the
keywordmodule. - Line 5: We store the list of keywords in
kwlistusingkeyword.kwlist. - Line 9: We initialize a string (paragraph) that contains keywords and non-keywords both.
- Line 13: We split the string into a list
string_listthat contains all words of the string. - Line 16–17: In a
forloop, all words in the list are checked to see if they belong tokwlist. - In the output, all words in
string_listare printed, along with abooleanvalue indicating whether they are a reserved keyword or not.