Python Reserved Words List - Your Complete Guide

There is a restriction while naming identifiers that there are some restricted words that are built-in to Python which cannot be used as an identifier. Python reserved words (also called keywords) a predefined meaning and syntax in the language which Python uses for its syntax and internal processing. In this tutorial, we will discuss what those keywords are.

Table of contents

Reserved words in Python

Here is the list of all the reserved words in Python.
Note - This list may change with different versions of Python. Python 3 has 33 while Python 2 has 30 reserved words. The print was removed from Python 2 keywords and added as a built-in Python function.

False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class form or
continue global pass

All the keywords except True, False and None are in lowercase and they must be written as they are. These cannot be used as variable names, function names, or any other identifiers.
If any of the keywords is used as a variable, then we will get the error message SyntaxError: invalid syntax

Keywords

False

It is a boolean operator that represents the opposite of True.

Input:

print (5 == 10)

Output:

FALSE

Since the values are not actually equal, it returns False.

def

The def function is used to define a function or a method in Python.

Input:

def welcome(name):
       print (f"{name}, Welcome to Flexiple")

welcome ("Ben")

Output:

Ben, Welcome to Flexiple

A function 'welcome' is defined using the def statement.

if

An if statement is used to make a conditional statement. If the condition is True, then some action is performed.

Input:

age = 19
If age >= 18:
       print ("You are eligible to vote.")

Output:

You are eligible to vote.

Since the age is greater than 18, the condition is True and the print command is executed.

raise

The raise statement is used to raise an error. These errors are visible in the traceback and they cancel the execution of the program if not handled properly.

Input:

enter = "nick"
if not type(enter) is int:
       raise TypeError("Only integers are allowed.")

Output:

TypeError: Only integers are allowed

TypeError is raised if the variable does not contain integers.

None

There is no null value in Python. The None is an object that represents the absence of a value. It is like an empty object.

Input:

age = None
if age is None:
       print ("Invalid result")

Output:

Invalid result

The age variable has no value to it. This satisfies the condition in the if statement.

del

The del statement is used to delete an object in Python.

Input:

name = [‘Ben’, ‘Nick’, ‘Steph’]
del name[1]
print (name)

Output:

[‘Ben’, ‘Steph’]

'Nick' is removed from the list.

import

This statement is used to import modules to the project.

Input:

import numpy
import math

This statement will import the NumPy and the math library into the project.

return

This keyword is used to exit a function or a method and return some value.

Input:

def sub(x, y):
       return x + y
print (sub(5, 4))

Output:

1

The function returns the sum of the two variables.

True

It is a boolean operator that represents if the value is True

Input:

print (10 == 10)

Output:

TRUE

The values are same so it returns True.

elif

Shorthand for else if, checks if some other condition holds when the condition in the if statement is false.

Input:

age = 18
if age > 18:
       print ("You are eligible to vote.")
elif age == 18:
       print ("You can vote if you are a registered voter.")
else: 
print ("You are not eligible to vote.")

Output:

You can vote if you are a registered voter.

The condition in the if statement was not True. Hence, the elif statement looked for other conditions that are True.

in

The in statement is used to check if an element is present in an iterable like list or tuple.

Input:

name = ['Ben', 'Nick', 'Steph']
exist = 'Steph' in name
print (exist)

Output:

TRUE

'Steph' is present in the name list.

try

The try statement is used to make a try… except statement. The try statement starts a block of code that is tried to execute. If it fails, the except block catches the error.

Input:

a = 5
b = 0 
try:
       div = a/b
except ZeroDivisionError:
       print ("Divisor cannot be zero.")

Output:

Divisor cannot be zero.

The divisor is 0, which is not possible. So the except block catches the error.

and

It is one of the logical operators that returns True if both of the statements are True.
The Truth table for the and operator is as follows:

A B A and B
True True True
True False False
False True False
False False False

Input:

a = 5
b = 10
c = 20
stat1 = b > a
stat2 = c > b
result = stat1 and stat2
print (result)

Output:

TRUE

Both the statements are True and that is why the and operator returns True.

else

Conditional statement that tells to perform alternate action if the condition in the if statement is False.

Input:

age = 16
if age >=18:
       print ("You are eligible to vote.")
else:
       print ("You are not eligible to vote.")

Output:

You are not eligible to vote.

The condition in the if statement was not True, so the alternate action is executed.

is

This statement is used to check if the two variables are equal.

Input:

a = 5
b = 5
print (a is b)

Output:

TRUE

Both the variables point to the same memory place.

while

This statement is used to start a while loop. It continues iteration until a condition is no longer True.

Input:

num = [1, 2, 3]
i = 0

while i < len(num):
       print (num[i])
       i = i + 1

Output:

1
2
3

The loop will run till the value of i is greater than the length of the list.

as

The as statement in Python re-assigns a returned object to a new identifier. Basically, it creates an alias.

Input:

import datetime as dt

today = dt.date.today()
print(today)

The datetime is identified as dt in the code.

except

Part of the type… except errorhandling structure in Python. Tells what to do when an exception occurs.

Input:

a = 5
b = 0 
try:
       div = a/b
except ZeroDivisionError:
       print ("Divisor cannot be zero.")

Output:

Divisor cannot be zero.

As the divisor was zero, the except code block caught the error.

lambda

A lambda function in Python is an anonymous function. It can take any number of arguments but only have a single expression.

Input:

numbers = [1, 2, 3]
cube_nums = map(lambda x: x ** 3, numbers)
print(list(cube_nums))

Output:

[1, 8, 27]

The cube of the variable is an anonymous function.

with

The with statement is used to simplify the exception handling.

Input:

with open("file.txt", "r") as file:
    lines = file.read()

assert

The assert statement in Python is used for debugging.

Input:

def divide(a, b):
    assert b != 0, "Divisor cannot be zero."
    return a / b

divide (5, 0)

Output:

Divisor cannot be zero.

finally

The finally statement is an optional part of try… except error. It always executes the code regardless of whether an error was thrown or not.

Input:

a = 5
b = 0 
try:
       div = a/b
except ZeroDivisionError:
       print ("Divisor cannot be zero.")
finally:
       print ("Error handling complete.")

Output:

Divisor cannot be zero.
Error handling complete.

The print statement under the finally will always execute no matter if there is an error or not.

nonlocal

This keyword is used in functions inside functions to create anonymous functions.

Input:

def outer():
  x = "Welcome"
  def inner():
    nonlocal x
    x = "to Flexiple"
  inner() 
  return x
print(outer())

Output:

to Flexiple

yield

The yield function ends a function and returns an iterator.

Input:

def nums():
    i = 0
    while True:
        yield i
        i += 1

for num in nums():
    print(num)

Output:

1
2
3
4
5
6
7
.
.
.

This is an infinity loop and will never end.

break

It is a control flow statement used to come out of a loop.

Input:

age = 19
if age >= 18:
       print ("You are eligible to vote.")
       break

Output:

You are eligible to vote.

As soon as the condition is satisfied, the break statement ends the loop.

for

The keyword is used to create a for loop.

Input:

num = [1, 2, 3]
cube = []
for number in num:
    cube.append(number ** 3)

print (cube)

Output:

[1, 8, 27]

This loop will run till all the elements in the list are gone through it.

not

It is another logical operator that returns False when the value is True and vice versa.
The truth table for not operator:

A not A
True False
False True

class

The class keyword is udes to define a class in Python.

from

This statement is used when you can to include a specific part of the module.

Input:

from math import sqrt
print(sqrt(9))

Output:

3

The whole math module is not imported, only a specific function is imported into the project.

or

It is a logical operator that returns True if any one of the statements is True.
Here is the truth table for or operator

A B A or B
True True True
True False True
False True True
False False False

Input:

stat1 = True
stat2 = False
result = stat1 or stat 2
print (result)

Output:

TRUE

One of the statements is True and according tot the truth table, the or operator will return True.

continue

It is a control flow statement used to continue to the next iteration of a loop. Unlike break, the continue statement does not exit the loop.

Input:

age = [12, 14, 15, 16, 18]
for number in age
print ("Not eligible")
if age >=18:
continue      
print ("You are eligible to vote.")
break

Output:

Not eligible
Not eligible
Not eligible
Not eligible
You are eligible to vote.

The condition in the if statement is not satisfied by the first element. The loop should end there but due tot he continue statement, the loop continues.

global

Accessing a global variable is simple as any other variable but to modify a global variable, you need to use the global keyword.

Input:

age = 18

def check():
       global age
       age = 16

check()
print (age)

Output:

16

The age variable is a global variable and we cannot change it's value without using the global statement.

pass

It is a null statement in Python that will do nothing.

Input:

def sub(a, b)
  pass
class Student
  pass

It is used as a placeholder for future code. It simply prevents getting errors when an empty code is run.

Display all keywords

We can display the full list of all the keywords in the current version of Python by typing the following command in the Python interpreter.

import keyword
print (keyword.kwlist)

And to find out the number of reserved words in Python.

print (len(kewyord.kwlist))

Check if the name is included in the reserved word list in Python

To check if the name is a part of the list of reserved keywords in Python, we can use the keyword.iskeyword() function.

Input:

import keyword
print (keyword.iskeyword(“global”))
print (keyword.iskeyword(“print”))

Output:

TRUE
FALSE

Closing Thoughts

Python reserved words designate special language functionality. No other variable can have the same name as these keywords. We read about all the reserved keywords and how to check if the name is a keyword or not. One can learn about more Python concepts here.