Keywords and reserved words in Python

Modified: | Tags: Python

You can check a list of Python keywords with the keyword module in the standard library.

The following sample code is running in Python 3.11.3. Note that the keywords may differ depending on the version.

The difference between keywords and reserved words

Strictly speaking, keywords and reserved words are different concepts.

Keywords have a special meaning in a language, and are part of the syntax.

Reserved words are words that cannot be used as identifiers (variables, functions, etc.), because they are reserved by the language.
...

In Python, at least as of Python 3.11, all keywords are reserved words, and there are no reserved words that are not keywords.

See also the following article for names that can be used as identifiers.

Get a list of Python keywords: keyword.kwlist

A list of keywords in Python is stored in keyword.kwlist.

In the following example, pprint is used to make the output easier to read.

import keyword
import pprint

print(type(keyword.kwlist))
# <class 'list'>

print(len(keyword.kwlist))
# 35

pprint.pprint(keyword.kwlist, compact=True)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
#  'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
#  'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
#  'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

The elements of the list are strings str.

print(keyword.kwlist[0])
# False

print(type(keyword.kwlist[0]))
# <class 'str'>

If these names are used as identifiers (variable names, function names, class names, etc.), an error is raised.

# True = 100
# SyntaxError: cannot assign to True

Check if the string is a Python keyword: keyword.iskeyword()

To check if a string is a keyword, use keyword.iskeyword().

It returns True if the specified string is a keyword and False if it is not. It is case-sensitive.

print(keyword.iskeyword('None'))
# True

print(keyword.iskeyword('none'))
# False

Related Categories

Related Articles