Python Keywords List

python keywords

Hello Techies,

Today we are covering the Python Keywords List. In this tutorial, we will check the list of all Python keywords according to the Python 3.8 version.

Table of Contents

What is Python Keywords?

  • Keywords are reserved words in Python.
  • Each keyword has a special meaning and operations.
  • Not all keywords are lowercase except for True, False, and None, and they should be written as they are.
  • You cannot use Python keywords for variable names, functions, classes, etc. This keyword has a special meaning and is used for special purposes in the Python programming language.

Type keywords to get a list of Python keywords:

We can also use the following code to get a list of all Python keywords.

>>> import keyword
>>> keyword_list = keyword.kwlist
>>> keyword_list

Output is:

['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']     

List of Keywords in Python

There are 35 Keywords in Python 3.8 version, this number may change slightly over time.

Here is a list of all Python keywords in Python 3.8.

Python Keywords List

Let’s check the usage of this Python keywords one by one with the help of example.

True, False keywords in Python

True and false Python keywords are used in comparison operations or logical (Boolean) operations in Python.

Example of True and False Python Keywords:

>>> 0==0
>>> True == False
>>> 8>7

None keyword in Python

  • It represents a null value.
  • This is not the same as 0, False, or an empty string, is a datatype of its own.

Example of None Keyword:

>>> None == 0
>>> None == False
>>> None == []
>>> a = None
>>> b = None
>>> a == b

and, or, not keywords in Python

  • These are logical operators in Python.
  • If both operands are True, the AND will return the True. 
  • OR returns True if one of the operand is true.
  • If the operand is False, NOT returns True.

Example of and, or & not Python Keywords:

>>> False and False
>>> False or True
>>> not True

in keyword in Python

  • in is the membership operator in Python.
  • This is used to find an element in the specified sequence.
  • It returns True if the element is found in the specified sequence else it returns False.
  • You can use this keyword in lists, tuples, and dictionaries.

Example of in keyword:

>>> str = "Welcome to TechPlusLifestyle"
>>> print("to" in str)

Also, this keyword is used in for loop.

>>> for each in "Python":
...     print(each)

is keyword in Python

  • This is an identity operator in Python.
  • This is used to compare whether two objects are the same or not.
  • It returns True if the memory location of two objects are the same else it returns False.

Example of is keyword:

>>> x = 10
>>> y = 10
>>> print(x is y)

for keyword in Python

The for loop is the most common loop in Python programming language. The for loop starts with for keyword, then you need to assign a variable that provides each element in the list, then the in keyword, and finally the sequence.

This is useful to iterate over the elements of sequence such as string, list, tuple, etc.

Example of for keyword:

>>> for each in ['P','Y','T','H','O','N']:
...     print(each)

while keyword in Python

while is used for looping in Python. In Python, while loops are used to reactivate a block of statements until a given condition is met.

while loop starts with while keyword, then you have to write the condition.

Example of while keyword:

>>> x = 1
>>> while x <= 6:
...     print(x)
...     x+=1

break, continue keywords in Python

  • We use break and continue in for and while loops to change their normal behavior.
  • break: Breaking through the loop even if the while or for condition is True.
  • continue: Allows you to stop the current iteration Continue until the next iteration of the loop.

Example of break, continue Python keywords:

#break keyword
for i in range(1,20):
    if i == 8:

#continue keyword
for i in range(1,20):
    if i == 8:

Output is:

#break keyword output

#continue keyword output

from, import, as keywords in Python

You need to import modules with the import keyword to use the functions in the modules in your script.

Python script import statements are declared at the top of the code. This is generally considered good practice of writing code.

Example of import keyword:

>>> import random
>>> import time
>>> print(random.randint(0,10))
>>> print(time.time())

The from keyword is used to import something specific from the module.

This will import whatever is in the module in your program. These two Python keywords (from, import) are used together.

Example of from keyword:

>>> from datetime import datetime
>>> print(
2021-01-08 16:48:30.504438

as keyword used to create aliases when importing modules. This means giving a different name when importing the module.

Example of as keyword:

>>> import calendar as cl
>>> print(cl.month_name[5])

assert keyword in Python

  • The assert is used for debugging purposes.
  • It is useful to ensure that a given condition is True. If it is not True, it raises AssertionError.
  • Syntax: assert condition, error_message
    • If the condition is False then the exception by the name AssertionError is raised along with the message.
    • If the message is not given and the condition is False, then also AssertionError is raised without a message.

Example of assert keyword:

>>> x = 15
>>> assert x <= 10
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>

We can also provide messages to print with AssertionError.

>>> x = 15
>>> assert x <= 10, 'Invalid Number'
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
AssertionError: Invalid Number

async, await keywords in Python

We know that asynchronous programming is a complex topic, so async, await Python keywords help to make this asynchronous code more readable and cleaner.

async keyword is used to define asynchronous function or coroutine with def. The syntax is similar to defining a function by initially adding async.

Example of async keyword:

async def fun_name(params):
    write code

await keyword is used to specify points in an asynchronous function where the event loop is given control to run other functions.


await <async function call>

Example of async/await keywords:

import asyncio

async def run_task():
    await asyncio.sleep(1)

# to run the run_task function

Output is:


return, yield keywords in Python

The return keyword can be used to return something from a function. In Python, it is possible to return one or more variables or values.

Syntax: return(variable or expression)

Example of return keyword:

>>> def add(number):
...     number+=1
...     return number
>>> add(5)

You can use the return keyword multiple times in one function. This allows you to get multiple exit points in your function.

Example of return keyword:

>>> def check_number_is_even(number):
...     if (number%2) == 0:
...             return True
...     else:
...             return False
>>> check_number_is_even(10)

yield keyword is works like a return keyword, but the yield returns a generator. yield returns the element from generator function into a generator object.

Generators are functions that return a sequence of values with the help of yield keyword.

Example of yield keyword:

>>> def python_frameworks():
...     yield 'Django'
...     yield 'Flask'
...     yield 'Pyramid'
>>> framework_list = python_frameworks()
>>> next(framework_list)
>>> next(framework_list)
>>> next(framework_list)  

if, else, elif keywords in Python

These Python keywords allow you to check the conditions.

The if keyword is used to initiate a conditional statement. An if statement allows you to write a block of code that is executed only if the expression is true.

Example of if keyword:

>>> x = 10
>>> if x%2 == 0:
...     print('Even Number')
Even Number

The elif statement looks and works like an if statement. This statement is always used with the if statement for the “else if” operation.

Example of elif keyword:

>>> x = 9
>>> if x > 10:
...     print('Greater than 10')
... elif x < 10:
...     print('less than 10')
... else:
...     print('Equal to 10')
less than 10

The else statement is used with the if-elif condition. Used to execute a statement when none of the previous conditions are True.

Example of else keyword:

>>> x = 10
>>> if x > 10:
...     print('Greater than 10')
... elif x < 10:
...     print('less than 10')
... else:
...     print('Equal to 10')
Equal to 10

try, except, raise keywords in Python

except, raise, try these Python keywords are used with exceptions in Python.

Exceptions are errors that indicate that something went wrong while running your program. ZeroDivisionError, IOError, ValueError, ImportError, NameError, TypeError, etc. are a few examples of exceptions in Python.

The Python try statement is used to write exception handling codes, while except keyword is used to catch the exceptions thrown in the try block.

Example of try and except Python keywords:

>>> x = ''
>>> try:
...     i = x + 2
... except Exception as e:
...     print(e)
can only concatenate str (not "int") to str

Using the raise keyword we can raise the exception. If you need to add an exception in your program, then you can use raise followed by the exception.

Example of raise keyword:

>>> x = ''
>>> if not isinstance(x, int):
...     raise TypeError("Require int argument")

finally keyword in Python

The finally statement is used with try-except statements to close the resource. The code in finally block is always executed.

Example of finally keyword:

>>> x = ''
>>> try:
...     i = x + 2
... except Exception as e:
...     print(e)
... finally:
...     ("This code will always execute")
can only concatenate str (not "int") to str
'This code will always execute'

with keyword in Python

with statement is used to wrap the execution of the block of code within methods defined by the context manager. The object must execute the __enter__() and __exit__() functions.

Example of with keyword:

with open('test.txt', 'w') as test_file:
    test_file.write('Hello Techies!')

lambda keyword in Python

The anonymous function is nothing but a function without a name. It is also known as Lambda Function. Anonymous Function is not defined using Def Keyword rather they are defined using lambda keyword.

Syntax: lambda argument_list: expression

Example of lambda keyword:

>>> sum = lambda x: x+5
>>> sum(5)
Interview Question:

Q: What is lambda function? Give example.
Ans: Just explain the above part about lambda function.

def keyword in Python

def Keyword used to define a function. A function is a block of related statements, which together perform a certain task. This helps us to manage the code and do some repetitive tasks.

Example of def keyword:

def function_name(arguments):
    write your code...

class keyword in Python

Class Keyword is used to define a class. Class is a collection of related properties, functions, and methods that try to represent real-world situations. The idea of putting data and functions together in the class is central to the concept of Object-Oriented Programming (OOP).

Example of class keyword:

class ClassName:
    def function1(arguments):
        write your code...
    def function2(arguments):
        write your code...

del keyword in Python

del keyword is used to delete variables, lists, objects, etc.

Example of del keyword:

>>> a = ['a','b','c']
>>> del a[2]
>>> print(a)
['a', 'b']
>>> str1 = "Python"
>>> print(str1)
>>> del str1
>>> print(str1)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'str1' is not defined

global keyword in Python

The global statement allows you to modify variables outside the current scope.

If you need to read the value of a global variable, you do not need to define it as global.

If we want to modify the value of the global variable in a function, we must declare it with global. Otherwise, a local variable with that name will be created.

Example of global keyword:

>>> x = 0
>>> def add():
...     global x
...     x += 1
>>> add()
>>> x
>>> add()
>>> x
>>> add()
>>> x

nonlocal keyword in Python

The nonlocal keyword is the same as global which allows you to modify variables from a different scope.

nonlocal keywords are used to access variables defined outside the scope of the block. It is always used in nested functions to access externally defined variables.

Example of nonlocal keyword:

>>> def outer_funct():
...     x = 1
...     def inner_funct():
...         nonlocal x
...         x = 9
...         print("Inner function: ",x)
...     inner_funct()
...     print("Outer function: ",x)
>>> outer_funct()
Inner function:  9
Outer function:  9

pass keyword in Python

In Python pass is a null statement. Nothing happens when it is executed. It’s useful when we need some statement but we don’t want to execute any code.

Example of pass keyword:

def function_name(arguments):

FAQ on Python Keywords

  1. How do I get a list of keywords in Python?

    You can use kwlist of keyword library to get a list of all Python keywords.
    Use below code:
    >>> import keyword

    >>> print(keyword.kwlist)

    Alternatively, you can get a list of all Python keywords using the Python Interpreter help utility.
    help> keywords

  2. Is assert a keyword in Python?

    Yes, The assert is used for debugging purposes.
    It is useful to ensure that a given condition is True. If it is not True, it raises AssertionError.

  3. Is sum a keyword in Python?

    No, Python provides an inbuilt function sum() which adds up the numbers in the list.

  4. Is none a keyword in Python?

    Yes, It represents a null value.
    This is not the same as 0, False, or an empty string, is a datatype of its own.

I hope you understand this list of Python keywords. Still, if you have any query about any of the Python keywords please comment below.

Check out the official site for more information about Python keywords.

Leave a Comment