Guide Python Beginner

4.6 Keywords

What Python keywords are, the complete keyword list for Python 3.12, using help('keywords'), and why keywords can't be used as identifiers.

6 min read

What Are Keywords?

What Is It?

Reserved words that are part of Python’s own syntax (if, for, def, class, …). The language grammar gives them special meaning, so they cannot be used as ordinary names.

Why Does It Matter?

Attempting to use a keyword as a variable name is a SyntaxError, not a warning.

>>> class = 5
  File "<stdin>", line 1
    class = 5
    ^^^^^
SyntaxError: invalid syntax

Complete Keyword List

Python 3.12 has 35 keywords, retrievable programmatically via the keyword module:

>>> import keyword
>>> keyword.kwlist
['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']
>>> len(keyword.kwlist)
35
flowchart TD K["35 Python Keywords"] K --> CF["Control Flow\nif / elif / else\nfor / while\nbreak / continue / pass"] K --> FC["Functions & Classes\ndef / return / class\nlambda / yield"] K --> LV["Logical / Values\nand / or / not\nTrue / False / None\nin / is"] K --> EH["Error Handling & Scope\ntry / except / finally / raise\nglobal / nonlocal\nimport / from / as"]

Python’s 35 keywords, grouped by purpose.

Hard Keywords vs Soft Keywords

Hard Keywords

Hard keywords are always reserved. The parser recognizes them wherever an identifier could otherwise appear, so names such as class, for, and return are invalid in every context.

class = "deployment"  # SyntaxError: invalid syntax

Soft Keywords

Soft keywords are reserved only in specific grammar contexts. In Python 3.10 and later, match and case are soft keywords used by structural pattern matching. The underscore (_) also has special pattern-matching behavior. Python 3.12 adds type as a soft keyword for type alias statements.

match status:
  case 200:
    message = "ok"
  case _:
    message = "unexpected status"

# Outside a match statement, these names can still be used normally.
match = "rolling"
type = "service"

Use keyword.softkwlist when code must account for contextual keywords as well as the hard keyword list:

>>> import keyword
>>> keyword.softkwlist
['_', 'case', 'match', 'type']

The exact list is version-dependent. Check the interpreter that will run the code rather than hard-coding a count.

Keywords by Role

RoleKeywordsTypical purpose
Decisions and loopsif, elif, else, for, while, break, continue, passSelect paths and repeat work
Functions and generatorsdef, return, lambda, yieldDefine callable code and produce values lazily
Classes and objectsclass, del, is, inDefine types, remove bindings, and test identity or membership
Exceptionstry, except, else, finally, raise, assertDetect, handle, raise, and validate failures
Imports and aliasesimport, from, asLoad modules and assign local aliases
Context managerswithAcquire and release resources predictably
Scopeglobal, nonlocalRebind names outside the current local scope
Boolean and special valuesand, or, not, True, False, NoneCombine conditions and represent values
Asynchronous codeasync, awaitDefine and suspend asynchronous operations

Checking Names Safely

An identifier must pass both checks: it must have valid identifier syntax and must not be reserved by the interpreter.

import keyword


def is_available_name(candidate: str) -> bool:
  return candidate.isidentifier() and not keyword.iskeyword(candidate)


for candidate in ("service_name", "2services", "class"):
  print(candidate, is_available_name(candidate))

Expected output:

service_name True
2services False
class False

str.isidentifier() checks the shape of a name; keyword.iskeyword() checks whether the interpreter reserves it. Neither check prevents shadowing a built-in such as list or type, so use clear project-specific names and follow 4.16 Coding Standards (PEP 8).

Practical DevOps Example

Keywords frequently appear in automation scripts that inspect command results and handle failures:

import subprocess


def check_service(service_name: str) -> str:
  try:
    result = subprocess.run(
      ["systemctl", "is-active", service_name],
      check=True,
      capture_output=True,
      text=True,
    )
  except subprocess.CalledProcessError as error:
    raise RuntimeError(f"Unable to inspect {service_name}") from error
  else:
    return result.stdout.strip()
  finally:
    print(f"Finished checking {service_name}")

Here, def, try, except, raise, from, else, and finally are keywords that define the control flow. The service name remains data supplied to the function, not a dynamically constructed piece of Python syntax.

How Python Handles a Keyword Error

Python parses source code before executing it. If a hard keyword appears where an identifier is required, parsing stops and no statements from that module run.

flowchart LR S[Source code] --> P{Parser} P -->|valid grammar| C[Compile bytecode] C --> R[Run program] P -->|keyword used as a name| E[SyntaxError] E --> X[Execution stops]

This is why a keyword naming error cannot be fixed with try/except: the try block itself cannot execute until the source has successfully parsed.

Using help('keywords')

How Is It Used?

The interactive help system lists and explains every keyword directly from the interpreter, without needing internet access:

>>> help("keywords")
Here is a list of the Python keywords.  Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
...

Restrictions

Keywords cannot be used as variable, function, or class names. Use keyword.iskeyword() to check programmatically before using a name you’re unsure about:

>>> keyword.iskeyword("for")
True
>>> keyword.iskeyword("variable")
False

Keywords Are Not the Same as Built-ins

class is a keyword and cannot be assigned. list, type, and id are built-in names, not hard keywords, so Python permits them but shadowing them can break later code:

list = ["api", "worker"]
print(list("abc"))  # TypeError: 'list' object is not callable

Use a descriptive name such as services instead. This distinction is a common interview follow-up.

Troubleshooting Checklist

When Python reports a keyword-related SyntaxError:

  1. Read the caret (^) location, then inspect the complete statement around it.
  2. Check whether a variable, function, parameter, or class has the same spelling as a hard keyword.
  3. Run python -m py_compile your_script.py to catch parse errors without executing the script.
  4. Check the interpreter version with python --version; keyword behavior can differ between Python versions.
  5. Rename the identifier rather than trying to quote or escape it. Python has no escape syntax that turns a keyword into an ordinary identifier.

Quick Interview Answer

“Keywords are the 35 reserved words baked into Python’s grammar — if, for, def, class, import, and so on. They can never be used as an identifier; trying raises a SyntaxError immediately, not a runtime warning. You can list them at any time with keyword.kwlist or check a specific name with keyword.iskeyword().”

Common Mistakes

  • Trying to name a variable class, type, or list — class is a hard keyword (fails outright); type and list are built-in names, not keywords, so they’re technically legal but silently shadow the built-in.
  • Assuming the keyword count never changes across versions — soft keywords such as match, case, _, and type behave contextually and are reported separately by keyword.softkwlist.
  • Trying to catch a keyword SyntaxError at runtime — parsing happens before execution, so the source must be corrected first.
  • Treating a keyword as the same thing as a built-in — keywords are grammar tokens; built-ins are ordinary names initially provided by the built-in namespace.

Interview Follow-up Questions

  1. What is the difference between a keyword, a soft keyword, and a built-in name?
  2. How can you list Python keywords programmatically?
  3. Why can a try/except block not catch class = 1?
  4. What are match and case, and why are they not in keyword.kwlist?
  5. How would you validate a user-provided name before generating Python source code?

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form