How to print keywords in Python

Learn to print keywords in Python. This guide covers various methods, tips and tricks, real-world applications, and debugging common errors.

How to print keywords in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Wed
Apr 8, 2026
The Replit Team

Python keywords are the reserved words that structure the language. You can print the full list for quick reference, which helps you avoid naming conflicts and understand Python's core syntax.

In this article, you'll learn techniques to display Python's keywords with the keyword module. You'll also find practical tips, see real-world applications, and get advice to debug common issues.

Using the keyword module to print all Python keywords

import keyword
print(keyword.kwlist)--OUTPUT--['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 keyword module offers a direct line to Python's reserved words. The code accesses the keyword.kwlist attribute, which is a list containing every keyword as a string for your current Python version.

This approach is both simple and reliable. You're not just getting a static list; you're pulling the exact keywords recognized by the interpreter you're running. This ensures the list is always accurate for your environment.

Basic keyword operations

Once you have the keyword list, you can move beyond simple printing and use Python's built-in tools to format, count, and analyze the words.

Formatting keywords for better readability

import keyword
for kw in keyword.kwlist[:5]:
print(f"Python keyword: {kw}")--OUTPUT--Python keyword: False
Python keyword: None
Python keyword: True
Python keyword: and
Python keyword: as

A for loop lets you handle each keyword individually. The example uses list slicing (keyword.kwlist[:5]) to process only the first five keywords, making the output more manageable. Inside the loop, an f-string adds a descriptive label before printing each word.

  • This technique is great for creating clean, readable logs.
  • You can also use it to integrate keywords into user-facing messages or structured reports.

Using list comprehension with the keyword module

import keyword
uppercase_keywords = [kw.upper() for kw in keyword.kwlist]
print(uppercase_keywords[:8])--OUTPUT--['FALSE', 'NONE', 'TRUE', 'AND', 'AS', 'ASSERT', 'ASYNC', 'AWAIT']

List comprehensions provide a concise, Pythonic way to create new lists. The expression [kw.upper() for kw in keyword.kwlist] builds a new list by applying the .upper() method to every item in keyword.kwlist. This single line achieves the same result as a multi-line for loop, but it's often more readable and efficient.

  • You get a new list, uppercase_keywords, without modifying the original.
  • This technique is ideal for transforming or filtering data in one go.

Counting keywords by length

import keyword
keyword_lengths = {len(kw): [] for kw in keyword.kwlist}
for kw in keyword.kwlist:
keyword_lengths[len(kw)].append(kw)
print(keyword_lengths[2]) # Keywords with 2 characters--OUTPUT--['as', 'if', 'in', 'is', 'or']

You can also categorize keywords, for instance, by grouping them based on their length. This code uses a dictionary to do just that. It first initializes a dictionary where each key is a keyword's length and the value is an empty list. A for loop then populates these lists by appending each keyword to the list corresponding to its character count.

  • This approach neatly organizes the keywords into buckets based on a shared property.
  • Accessing a group is simple—just use the length as a key, like keyword_lengths[2].

Advanced keyword techniques

Beyond organizing the list, you can use the keyword module to validate identifiers, filter keywords by custom criteria, and even access the module's own metadata.

Checking if words are Python keywords

import keyword
test_words = ['while', 'function', 'class', 'variable']
for word in test_words:
print(f"'{word}' is {'a keyword' if keyword.iskeyword(word) else 'not a keyword'}")--OUTPUT--'while' is a keyword
'function' is not a keyword
'class' is a keyword
'variable' is not a keyword

The keyword module includes a handy function, keyword.iskeyword(), to check if a string is a reserved word. The code iterates through a list of test words, using a conditional expression inside an f-string to print the result. This approach makes the validation logic compact and easy to read.

  • This function is crucial for validating potential variable or function names before you use them.
  • It returns True if the word is a keyword and False otherwise.
  • Using it helps prevent SyntaxError exceptions from naming conflicts with reserved words.

Filtering keywords by specific criteria

import keyword
control_flow = ['if', 'else', 'elif', 'for', 'while', 'break', 'continue', 'try', 'except', 'finally']
control_keywords = [kw for kw in keyword.kwlist if kw in control_flow]
print(control_keywords)--OUTPUT--['break', 'continue', 'elif', 'else', 'except', 'finally', 'for', 'if', 'try', 'while']

You can filter the full keyword list to isolate specific groups. The code uses a list comprehension to build a new list, control_keywords. It iterates through keyword.kwlist and includes only the words that are also present in the predefined control_flow list. This is a powerful way to create specialized subsets of keywords for analysis or validation.

  • This method is highly efficient for creating targeted lists from a larger collection.
  • You can adapt the condition to filter by any criteria, such as starting letters or length.

Working with keyword module metadata

import keyword
import sys

print(f"Python version: {sys.version.split()[0]}")
print(f"Total keywords: {len(keyword.kwlist)}")
print(f"'async' and 'await' in keywords: {'async' in keyword.kwlist and 'await' in keyword.kwlist}")--OUTPUT--Python version: 3.x.x
Total keywords: 35
'async' and 'await' in keywords: True

The keyword module is dynamic, meaning its contents depend on the Python version you're using. The code snippet confirms this by first printing your environment's Python version with sys.version. It then gets the total number of keywords for that version using len(keyword.kwlist).

  • This version-specific nature is why checking for keywords like async and await is useful.
  • Their presence confirms you're running a modern version of Python that supports asynchronous operations.

Move faster with Replit

Replit is an AI-powered development platform where you can start coding Python instantly. It comes with all Python dependencies pre-installed, so you can skip setup and focus on building. Instead of piecing together individual techniques, you can use Replit's Agent 4 to build complete applications from a simple description.

For example, you could ask the Agent to build:

  • A variable name validator that checks user input against Python's reserved words to prevent syntax errors.
  • A simple code analysis tool that scans a Python file and reports the frequency of different keywords.
  • An interactive learning utility that groups and displays keywords by their category, like control flow or boolean values.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While working with Python's keywords is usually straightforward, a few common pitfalls can trip you up if you're not careful.

Using a keyword as a variable name is a classic mistake that immediately results in a SyntaxError. For instance, an assignment like try = 5 is invalid because Python reserves try for exception handling. This error stops your program cold, so it's essential to ensure your variable, function, and class names aren't on the reserved list.

Another challenge arises when you don't validate user input that will be used as an identifier. If your application generates code and a user provides a name like while or if, you'll end up with broken syntax. Always run user-provided strings through keyword.iskeyword() to catch these issues before they cause problems.

Forgetting to import the keyword module before using it is a common oversight that leads to an AttributeError. If you try to access keyword.kwlist without the initial import keyword statement, Python has no idea what keyword refers to. The solution is simple—just make sure the import is present at the top of your file.

Avoiding the SyntaxError when using keywords as variable names

It's tempting to use a simple name like class for a variable, but doing so will trigger a SyntaxError. Python reserves this word for defining classes, so it can't be reassigned. The following code shows what happens when you try.

import keyword

class = "Advanced Python" # Trying to use 'class' as a variable
print(f"Course level: {class}")

The assignment class = "Advanced Python" fails because the interpreter expects a class definition to follow the class keyword. This mismatch triggers a SyntaxError. Check out the corrected version below to see a simple fix.

import keyword

class_name = "Advanced Python" # Using 'class_name' instead
print(f"Course level: {class_name}")

The fix is straightforward: rename the variable. By changing class to class_name, you create a valid identifier that doesn't conflict with Python's reserved words, resolving the SyntaxError.

This issue often appears when your variable's purpose is close to a keyword's meaning. It's a common convention to append an underscore, like class_, to avoid the conflict while keeping the name intuitive, especially when working with concepts like classes or functions.

Forgetting to check for keywords in user input validation

Relying solely on isidentifier() for validation is a common trap. This function confirms a string follows naming rules but doesn't check if it's a reserved keyword. The code below demonstrates how this oversight can approve an invalid variable name, leading to errors.

def validate_variable_name(name):
return name.isidentifier() # Only checks if it's a valid identifier

user_input = "if" # Could be from user input
if validate_variable_name(user_input):
print(f"Variable {user_input} is valid")

The function incorrectly approves 'if' because isidentifier() only confirms valid characters. It doesn't check against Python's reserved words, setting you up for a SyntaxError. The corrected code below shows a more robust validation approach.

import keyword

def validate_variable_name(name):
return name.isidentifier() and not keyword.iskeyword(name)

user_input = "if" # Could be from user input
if validate_variable_name(user_input):
print(f"Variable {user_input} is valid")
else:
print(f"'{user_input}' is a reserved keyword and cannot be used")

The fix strengthens validation by combining two checks. The function now confirms a string is a valid identifier with name.isidentifier() while also ensuring it’s not a reserved word using not keyword.iskeyword(name). This robust approach is essential in specific situations.

  • It's crucial for apps that generate code or define identifiers from user input.
  • It prevents SyntaxError exceptions by catching invalid names like if or while before they’re used.

Troubleshooting the AttributeError with direct kwlist access

It's easy to forget that keyword is a module, not a list. Trying to check for membership directly with in keyword won't work because you must access the kwlist attribute. This mistake can cause an AttributeError or similar issues. The code below demonstrates this common pitfall.

import keyword

if "yield" in keyword: # Incorrect: trying to check if 'yield' is in the module
print("'yield' is a Python keyword")

The code attempts to use the in operator on the keyword module itself, which isn't a collection of strings. This action triggers a TypeError because modules don't support membership tests. See the corrected approach below.

import keyword

if "yield" in keyword.kwlist: # Correct: checking the kwlist attribute
print("'yield' is a Python keyword")

The fix is to target the kwlist attribute for the membership test. The keyword module is an object, not an iterable list, so using the in operator on it directly causes an error. By specifying keyword.kwlist, you're correctly checking for the string within the list of keywords.

  • This mistake often happens when you treat a module like a simple data structure.
  • Always access the specific attribute you need, like kwlist.

Real-world applications

Knowing how to handle keywords isn't just about fixing errors; it's fundamental to building reliable, real-world tools that manage code dynamically.

Using the iskeyword() function to detect variable conflicts

You can use the iskeyword() function to automatically scan code and flag variable names that conflict with Python's reserved words.

import keyword

# Sample code with variables that shadow Python keywords
code_variables = ["user", "class", "name", "if", "age"]

# Check for keyword shadowing
for var in code_variables:
if keyword.iskeyword(var):
print(f"Warning: '{var}' shadows a Python keyword")
else:
print(f"'{var}' is a safe variable name")

This code simulates a script that checks for naming conflicts. It loops through a list of potential variable names stored in code_variables. For each name, it uses the keyword.iskeyword() function to determine if the string is a reserved word in Python.

  • This is a fundamental technique for any application that generates or manipulates code.
  • It allows you to validate identifiers programmatically, ensuring you don't create code with a SyntaxError.

Creating a safe configuration system with keyword validation

You can prevent syntax errors from configuration files by validating keys with keyword.iskeyword() and renaming any that conflict with Python's reserved words.

import keyword

# Create a configuration dictionary
config = {"username": "admin", "class": "Administrator", "if": True}

# Create a safe version by renaming keyword entries
safe_config = {}
for key, value in config.items():
if keyword.iskeyword(key):
safe_config[key + "_config"] = value
else:
safe_config[key] = value

print(safe_config)

This code shows a practical way to clean up dictionary keys. It iterates through a config dictionary where some keys, like class and if, are reserved Python words. Using keyword.iskeyword(), it identifies these conflicting keys and creates new, safe versions by appending _config.

  • Non-keyword keys are copied directly to the new dictionary.
  • Keyword keys are renamed before being added (e.g., class becomes class_config).

The result is a sanitized safe_config dictionary, ready for use without risking syntax errors from reserved words.

Get started with Replit

Turn these techniques into a real tool. Ask Replit Agent to build "a Python script linter that flags keyword conflicts" or "a utility that validates variable names from a CSV file."

The Agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit and see your tool run in seconds.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.