Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Literals in Python?
3.
Difference Between String and Literal in Python?
4.
Types of Literals in Python
4.1.
Numeric Literals in Python
4.1.1.
Implementation
4.1.2.
Implementation
4.2.
String Literals in Python
4.2.1.
Implementation
4.2.2.
Implementation
4.3.
Boolean Literals in Python
4.3.1.
Implementation
4.3.2.
Implementation
5.
Literal Collection 
5.1.
1. List literals 
5.1.1.
Implementation
5.2.
2. Tuple literals 
5.2.1.
Implementation
5.3.
3. Dictionary literals 
5.3.1.
Implementation
5.4.
4. Set Literals
5.4.1.
Implementation
6.
Special Literals in Python
6.1.
Implementation
7.
Uses of Literals in Python
7.1.
1. Assigning values to variables
7.2.
2. Passing arguments to functions
7.3.
3. Initializing data structures 
7.4.
4. Comparing values 
7.5.
5. Testing code
8.
Frequently Asked Questions
8.1.
What is an example of a literal in Python?
8.2.
What are the 3 literals in Python?
8.3.
What is the literal 1 in Python?
8.4.
What are two examples of literals?
8.5.
What is the difference between a literal and a datatype in Python?
9.
Conclusion
Last Updated: Mar 28, 2024
Easy

Literals in Python

Author Tashmit
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Hey, Ninjas! Do you know that Python is a fascinating programming language in which Literals play an essential role? In this article, we will discuss about literals in Python, their types and their uses. Literals play an essential role in expressing data, such as numbers, strings, and Boolean values.

So let's dive in and discover the power of literals!

 literals in python

What are Literals in Python?

A literal in Python is a notation representing a fixed value in the Python source code. It is a way of declaring a value without using variables or expressions. Literals can be used to describe various data types of values, such as numeric, strings, and boolean values. Literals in python are of many types. Let us have a look on various types of literals.

Also see, Python Operator Precedence and leap year program in python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Difference Between String and Literal in Python?

ParametersStringLiteral
DefinitionA sequence of characters enclosed in quotes (single or double).A fixed value is directly expressed in the code.
ContainsIt can be assigned to variables and manipulated using string methods.Does not require assignment to a variable and represents data directly.
ModificationsIt can be concatenated, sliced, and modified using various string operations.It cannot be modified, as literals are immutable values.
ExamplesExamples: "Hello, World!", 'Python is awesome!'Examples: 42, 3.14, True, False
UsageUsed for representing textual data in Python.Used for representing fixed values such as numbers, Booleans, and other constant data.

Types of Literals in Python

There are various types of Literals on Python. Let’s Explore the diverse forms of literals that Python offers, from numeric literals and string literals to Boolean literals and more.

Types of Literals in Python

Numeric Literals in Python

Numeric literals contain numeric values in Python. They include all the integer, float, long, or decimal values. Let us see some examples to better understand it.

As the name suggests, integer literals are used to store integer values like 47, 0, -985, etc. It can store binary, decimal, hexadecimal, or octal values as well.

Implementation

num1 =42
num2 =-123
num3 =0

num4 =0b1010 # represents decimal 10
num5 =-0B110 # represents decimal -6

num6 =0o52 # represents octal 42
num7 =-0O76 # represents octal -62

num8 =0x2A # represents hexadecimal 42
num9 =-0X1A # represents hexadecimal -26

print(num1,num2,num3,num4,num5,num6,num7,num8,num9)


The output of this code will be:

Output

If you want to store float value, it can be done in similar way,

Implementation

num1 =18.5
num2 =87.3
print(num1, num2)

 

Output

Output

String Literals in Python

String literals are used to store textual data in Python. They contain ASCII characters, including letters, special characters, or white spaces. Let us see some examples.

str1 ="Coding Ninjas"
print(str1)


The above code is an example of a single line string. As the name suggests, it stores a single line of data.

This will print Coding Ninjas as output

Output

If you want to store a multiple line string literal, we can code it as:

str1 ='''I
am
a
ninja'''
print(str1)

 

The output of this code will be:

Output

We can also do that with the use of a backslash. For example,

Implementation

str2 ="\"I'm a coder!\""
print(str2)

 

This will generate the following output:

Output

We can also concatenate two strings with the ‘+’ operator.

Implementation

str1 ="Welcome "
str2 ="to "
str3 ="Coding Ninjas!"
print(str1 + str2 + str3)

 

This will generate the output as follows:

Output

Boolean Literals in Python

As you know, boolean values can only have two values, True or False. Therefore, boolean literals are predefined values as True and False. We can use it in conditional statements or loops like:

Implementation

num =1605

if num >1000:
 print("num is greater than 1000")
else:
 print("num is less than or equal to 1000")

 

In this example, the value of num > 1000 is True. Therefore, the output is:

Output

Boolean literals in Python can also be used with logical operators such as 'or,' 'and', and 'not.'

Implementation

a =True
b =False
c =a and b
d =a or b
print(c,d)

 

Here, c contains the True and False value; therefore, it will be False. And d has values of True or False. Hence it will generate output as True.

Output

Literal Collection 

In Python, literal collections are used to represent collections of values of the same or different data types. Python provides several types of literal collections, including lists, tuples, and dictionaries.

1. List literals 

List literals are used to represent ordered sequences of values in Python. They are enclosed in square brackets, with each value separated by a comma. For example:

Implementation

ninja_list =[16,25,"Python",3.629]
print(ninja_list)

 

The output of above code is:

Output

2. Tuple literals 

Tuple literals are similar to list literals, but they are enclosed in parentheses instead of square brackets. They also represent ordered sequences of values, but unlike lists, they are immutable (cannot be changed). For example:

Implementation

ninja_tuple =(16,25,"Coding Ninjas",True)
print(ninja_tuple)

 

The above code will generate a tuple literal and give output as:

Output

3. Dictionary literals 

Dictionary literals are used to represent mappings between keys and values in Python. They are enclosed in curly braces, with each key-value pair separated by a colon. For example:

Implementation

ninja_dict = {"Name": "Ninja1", "Age": 25, "Country": "India"}
print(ninja_dict)

 

The above code will generate the output as follows:

Output

4. Set Literals

In addition to these literal collections, Python also provides other types of collections, such as sets and frozensets. Sets are unordered collections of unique values, while frozensets are immutable sets. Here is an example of a set literal:

Implementation

ninja_set ={1,2,3,4,5}
print(ninja_set)

 

This will give output as:

Output

Special Literals in Python

In Python, special literals are values that have a special meaning in the language. They are used to represent values that do not belong to any of the standard data types, such as integers, strings, or lists. In Python the special Literal is ‘None’.

It represents the absence of a value. It is often used to indicate that a variable has not been initialized or a function does not return a value. For example:

Implementation

ninja_var =None
if ninja_var is None:
 print("ninja_var is not initialized")
else:
 print("ninja_var is initialised")

 

As the ninja_var has None value, therefore, the output will be:

Output

Uses of Literals in Python

Literals in Python are used to represent specific values of different data types. They are used for various purposes in Python programming, such as:

1. Assigning values to variables

Literal values are often used to assign values to variables in Python.

2. Passing arguments to functions

We can pass literal values as arguments to functions in Python. 

3. Initializing data structures 

We can initialize data structures such as lists, tuples, and dictionaries using literal values.

4. Comparing values 

We can use literal values to compare with other values in Python.

5. Testing code

Literal values are also used for testing code in Python. By assigning literal values to variables, we can test the behavior of our code and ensure that it works correctly.

Check out this article - Quicksort PythonSwapcase in Python

Must Read Invalid Syntax in Python.

Frequently Asked Questions

What is an example of a literal in Python?

An example of a numeric literal is, say, 42 or for a string, it would be “John”, which represents the integer value 42. Literals are fixed values used to express data directly in the code.

What are the 3 literals in Python?

The three main literals in Python are numeric literals ( e.g., integers, floating point numbers like 42 ), string literals ( e.g., "hello", "john", "jane" ), and Boolean literals ( e.g., True, False ). They directly represent data within the code.

What is the literal 1 in Python?

Python has just two Boolean literals that, are True and False. In Python, True corresponds to the value 1, while False corresponds to the value 0.

What are two examples of literals?

Two examples of literals in Python are the string literal "Hello, world!" and the Boolean literal True. They directly represent a sequence of characters and a Boolean value, respectively, without the need for variables or expressions.

What is the difference between a literal and a datatype in Python?

A literal in Python refers to the data given in a variable or constant. It represents fixed values in the code like 2, "Hello", 3.14, etc whereas datatype in Python refers to the class of data that a variable can hold. Python has several data types like integers (int), floating-point numbers (float), strings (str), and others.

Conclusion

In this article, we focused on learning about Literals in Python and its various types. We hope this blog has helped you in enhancing your knowledge. You can refer to Python applicationsConvert String to List Python and Python list operations to know more.

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy Learning Ninja!

Previous article
Python Matplotlib
Next article
Top Python Applications
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass