PythonIntroduction to PythonPython fundamentals

What are Python keywords?

Question 17 of 20 · Updated

On this page

Python keywords are words with predefined meanings in the Python language grammar. They express operations and structures such as conditional statements, loops, function definitions, exception handling, imports and logical expressions.

Ordinary reserved keywords cannot be used as variable names, function names or other identifiers in Python source code. For example, class is reserved because it introduces a class definition. Python also has soft keywords, which have special meanings only in particular grammatical contexts.

Understanding the difference helps you read Python programs, choose valid names and avoid syntax errors.

1. How many keywords are there in Python?#

Python 3.13 has 35 reserved keywords and four soft keywords. The count is version-dependent: Python can add keywords or change their status when the language evolves.

Use the standard-library keyword module to inspect the interpreter you are actually running:

PYTHON
import keyword print(keyword.kwlist) print(len(keyword.kwlist)) print(keyword.softkwlist)

Output on Python 3.13.5:

['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']
35
['_', 'case', 'match', 'type']

Do not hardcode a universal keyword count in software intended to support several Python releases. Use keyword.kwlist for the running interpreter, or validate against the grammar of the specific target release when generating code for another version.

2. Complete list of Python reserved keywords#

The following table groups all 35 Python 3.13 reserved keywords by their principal use. Several keywords can participate in more than one grammatical structure.

CategoryKeywordsPurpose
Special valuesFalse, None, TrueBoolean values and the absence-of-value singleton
Boolean operatorsand, or, notLogical operations and short-circuit evaluation
Membership and identityin, isMembership and object identity tests; in also appears in iteration syntax
Conditional executionif, elif, elseSelect branches based on conditions
Iterationfor, whileRepeat work over an iterable or while a condition is true
Loop controlbreak, continueExit the innermost loop or advance to its next iteration
Empty statementpassProvide a syntactically valid statement that does nothing
Functions and classesdef, class, lambdaDefine functions, classes and anonymous function expressions
Function resultsreturn, yieldReturn from a function or produce values from a generator
Exception handlingtry, except, finally, raise, assertHandle, raise or check exceptional conditions
Imports and aliasesimport, from, asImport names, bind aliases and support related grammar constructs
Scope declarationsglobal, nonlocalDeclare how certain name bindings are resolved
Name or item deletiondelDelete a name binding, attribute or item, subject to object behaviour
Resource managementwithEnter and exit a context manager
Asynchronous programmingasync, awaitDefine asynchronous constructs and await awaitable objects

Some important combinations are formed from multiple keywords, such as is not, not in, async def, async for and async with. These combinations are not additional individual reserved words.

3. Are Python keywords case-sensitive?#

Yes. Python source code is case-sensitive. The spelling of a reserved keyword must match the language grammar exactly.

PYTHON
import keyword print(keyword.iskeyword("class")) print(keyword.iskeyword("Class")) print(keyword.iskeyword("print"))

Output:

True
False
False

class is reserved, but Class is not. That does not mean Class is a good variable name: naming conventions still matter.

True, False and None begin with capital letters. Lowercase true, false and none are not equivalent built-in constants. If you use an unbound name such as true, Python ordinarily raises NameError when evaluating it.

4. What are soft keywords in Python?#

A soft keyword is recognised as a keyword only in specific syntactic contexts. Elsewhere, the same spelling can generally be an ordinary identifier.

In Python 3.13, the soft keywords are:

Soft keywordSpecial context
matchIntroduces a structural pattern-matching statement
caseIntroduces a pattern-matching case
_Wildcard pattern in the appropriate pattern-matching context
typeIntroduces a type alias statement

Structural pattern matching introduced match, case and the wildcard use of _ in Python 3.10. The type alias statement introduced type as a soft keyword in Python 3.12.

PYTHON
import keyword print(keyword.issoftkeyword("match")) print(keyword.iskeyword("match")) match = "label" print(match)

Output on Python 3.10 or later:

True
False
label

Although match has a special grammatical role, assigning to a variable named match is valid outside that role.

The following example uses structural pattern matching, available in Python 3.10 and later:

PYTHON
status = 404 match status: case 200: print("OK") case 404: print("Not found") case _: print("Other")

Output:

Not found

Here match and case introduce pattern-matching constructs, and _ is a wildcard pattern. The wildcard does not bind the matched value to a variable.

Soft keywords help Python introduce new syntax while reducing conflicts with existing code. However, using a soft keyword as an ordinary name may still confuse readers, especially in code involving the related feature.

5. Examples of Python keywords in action#

PYTHON
def valid(score): return score >= 0 and score <= 100 print(valid(75)) print(valid(-1))

Output:

True
False

def defines a function, return exits the function with a value, and and combines two conditions. When the left operand of and is falsy, Python does not evaluate the right operand.

In general, and and or return one of their operands rather than necessarily returning a Boolean. Here both operands are comparisons, so the result is a Boolean.

Conditional and loop-control keywords#

PYTHON
for number in range(5): if number == 2: continue if number == 4: break print(number)

Output:

0
1
3

for introduces the loop, in connects the loop target to the iterable, if tests conditions, continue skips the remainder of the current iteration, and break exits the loop. range and print are built-in callable objects, not reserved keywords.

Special values, membership and identity#

PYTHON
def classify(value): if value is None: return "missing" if value in ("", "unknown"): return "unspecified" return "present" for value in [None, "", "ready"]: print(classify(value))

Output:

missing
unspecified
present

None is a special singleton used to represent the absence of a value. is tests object identity, so is None is the usual idiom for checking it. in checks membership in the tuple. The function intentionally distinguishes None from an empty string.

These examples demonstrate grammatical roles. Each topic, such as exception handling, asynchronous programming and scope, has further semantics that should be studied separately.

6. What happens if you use a reserved keyword as a variable name?#

Python rejects invalid source code during parsing. The following assignment is intentionally invalid:

class = 1

It causes SyntaxError because class is reserved and cannot appear as the assignment target in this form.

To demonstrate the error safely without making the whole example file invalid, compile the source string and catch SyntaxError:

PYTHON
try: compile("class = 1", "<example>", "exec") except SyntaxError: print("Reserved keyword cannot be assigned")

Output:

Reserved keyword cannot be assigned

Use an alternative name such as class_name or, where a conflicting interface name must be accommodated, class_. A descriptive name is generally preferable to an arbitrary spelling change.

A syntax error is different from a NameError. An ordinary valid identifier that has not been bound can produce NameError during execution; a reserved keyword used in an invalid grammatical position prevents the source from being parsed correctly.

7. Keywords vs identifiers vs built-in names#

These terms describe different aspects of Python.

ConceptMeaningExamples
Reserved keywordReserved spelling recognised by the language grammarif, class, return
Soft keywordSpecial spelling in certain grammar contextsmatch, case, type
IdentifierName used to identify a binding or other named constructtotal_price, calculate_total
Built-in nameName supplied by Python's builtins namespaceprint, len, list, type
String literalSource notation representing a string value"class", "return"

Built-in names are generally not reserved words. It is syntactically possible to assign a value to list or print, but doing so may shadow the corresponding built-in within the relevant scope. This can cause surprising errors when later code tries to call the original built-in.

The name type is both a built-in name and, from Python 3.12 onward, a soft keyword. These roles are not mutually exclusive.

Reserved spellings can appear as string values, dictionary keys or text in comments because those are not ordinary identifier positions. For example, a dictionary received from an external API may contain a string key named "class".

8. How do you check whether a word is a valid identifier?#

The keyword module provides keyword.iskeyword() and, in Python 3.9 and later, keyword.issoftkeyword(). A string's isidentifier() method checks whether its spelling meets Python's lexical identifier rules, but does not by itself reject reserved keywords.

For ordinary source-code names, combine isidentifier() with a reserved-keyword check:

PYTHON
import keyword def valid_name(name): return name.isidentifier() and not keyword.iskeyword(name) for name in ["total", "class", "2items", "match"]: print(name, valid_name(name))

Output on Python 3.13.5:

total True
class False
2items False
match True

class has the shape of an identifier but is a reserved keyword. 2items is rejected because an identifier cannot begin with an ASCII digit. match is permitted as an ordinary name in the tested context.

This function checks ordinary naming eligibility in the running interpreter. It does not guarantee that a name is meaningful, avoids collisions with existing bindings or works in every grammar context. For code generators, additional validation may be necessary, including handling soft keywords, Unicode normalisation, scope collisions and the target language version.

9. Are keywords the same as keyword arguments?#

No. A reserved keyword belongs to the language grammar. A keyword argument supplies an argument to a callable using a parameter name.

PYTHON
def greet(name): return f"Hello, {name}" print(greet(name="Asha"))

Output:

Hello, Asha

In greet(name="Asha"), name is the keyword argument's name. It is an ordinary identifier, not a Python reserved keyword. The reserved words in this example are def and return.

This distinction becomes important when studying positional arguments, keyword-only parameters and **kwargs.

10. Practical considerations for developers#

Python keywords affect syntax highlighting, source-code generation, static analysis and compatibility checks.

For example, if a code generator receives database column names and converts them into Python attributes, a column named class cannot be emitted unchanged as an ordinary source-code identifier. A generator should produce a valid, collision-free name while preserving the original column mapping. It must also account for target-version grammar and avoid treating untrusted text as executable code.

For manually written application code:

  • Choose descriptive names rather than reserved words.
  • Avoid shadowing common built-ins such as list, str, id and print.
  • Use the keyword module to inspect the actual interpreter instead of relying on memorised counts.
  • Treat soft keywords according to their grammatical context and Python version.
  • Use a linter to catch confusing naming choices and a parser or compiler to validate generated source.

A lexical name check is not a security mechanism. It does not make arbitrary generated source safe to execute.

11. Common mistakes and misconceptions#

Assuming every Python command is a keyword#

print, len, range, int and many familiar names are built-ins. They are not reserved keywords. Python 2 had a print statement, but Python 3 uses print as a function.

Assuming isidentifier() rejects all reserved words#

It validates lexical form. Combine it with keyword.iskeyword() when checking ordinary source names.

Treating match, case, type and _ as permanently reserved#

These are soft keywords in Python 3.13. Their special roles depend on grammar context, and availability varies with Python version.

Treating None, False and zero as interchangeable#

They have different meanings. For example, a configuration value of zero may be valid even when None represents an unspecified setting. Use an explicit identity check when the distinction matters.

Confusing pass and continue#

pass does nothing and execution proceeds to the next statement. continue skips the remaining statements in the current loop iteration and proceeds to the next iteration.

12. Frequently asked questions#

Can Python keywords be redefined?#

Reserved keywords cannot be assigned new meanings through ordinary variable or function definitions. Their interpretation is governed by the language grammar.

Is self a Python keyword?#

No. self is the conventional first parameter of an instance method. Python does not reserve the spelling.

Is async a Python keyword?#

Yes, async and await are reserved keywords in Python 3.7 and later. Earlier Python versions treated them differently.

Are soft keywords included in keyword.kwlist?#

No. Inspect keyword.softkwlist separately on versions that provide it.

Is the number of Python keywords always 35?#

No. It is 35 in Python 3.13, but the language evolves. Query the runtime's keyword module or consult the appropriate version of the language reference.

13. Interview-ready answer#

Python keywords are reserved words that carry predefined meanings in the language grammar. Examples include if, for, def, class, return, try, async and await. Ordinary reserved keywords cannot be used as identifiers. Python 3.13 has 35 reserved keywords and four soft keywords, whose special meanings depend on context. You can inspect them using keyword.kwlist, keyword.softkwlist and keyword.iskeyword(). Built-in names such as print and len are not reserved keywords, and keyword arguments are a separate concept.

Key takeaways#

  • Keywords are grammatical building blocks, not simply predefined functions.
  • Python keywords are case-sensitive.
  • Reserved keywords and soft keywords have different restrictions.
  • Use the keyword module for version-specific lists and checks.
  • Combine str.isidentifier() and keyword.iskeyword() when validating ordinary names.
  • Avoid shadowing built-ins even where Python allows the spelling.

Official references#

Verification note: Nine standalone Python examples were executed and their outputs checked locally on Python 3.13.5; the reserved and soft keyword lists and counts were also inspected on that interpreter. The deliberately invalid source line is demonstrated using compile() with exception handling. Official links are provided from established knowledge under the authorised offline research exception; live documentation was not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design