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 module
import keyword
#print kwlist
kwlist = keyword.kwlist
print(kwlist)
#intialize test strings
string = '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 kwlist
for word in string_list:
print(word,': ', word in kwlist)

Explanation

  • Line 2: We import the keyword module.
  • Line 5: We store the list of keywords in kwlist using keyword.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_list that contains all words of the string.
  • Line 16–17: In a for loop, all words in the list are checked to see if they belong to kwlist.
  • In the output, all words in string_list are printed, along with a boolean value indicating whether they are a reserved keyword or not.