Table of contents
1.
Introduction
2.
What are Literals in Python?
3.
Types of Literals in Python
4.
Numeric Literals in Python
4.1.
Integer
4.2.
Float 
4.3.
Long
4.4.
Decimal Values
4.4.1.
Implementation
4.5.
Python
4.5.1.
Implementation
4.6.
Python
5.
String Literals in Python
5.1.
Single-line String
5.2.
Python
5.3.
Multi-line String
5.4.
Python
5.4.1.
Implementation
5.5.
Python
5.5.1.
Implementation
5.6.
Python
6.
3. Boolean Literals in Python
6.1.
Implementation
7.
Python
7.1.
Implementation
8.
Python
9.
4. Literal Collection 
9.1.
1. List literals 
9.1.1.
Implementation
9.2.
Python
9.3.
2. Tuple literals 
9.3.1.
Implementation
9.4.
Python
9.5.
3. Dictionary literals 
9.5.1.
Implementation
9.6.
Python
9.7.
4. Set Literals
9.7.1.
Implementation
9.8.
Python
10.
5. Special Literals in Python
10.1.
Implementation
11.
Python
12.
Uses of Literals in Python
12.1.
1. Assigning values to variables
12.2.
2. Passing arguments to functions
12.3.
3. Initializing data structures 
12.4.
4. Comparing values 
12.5.
5. Testing code
13.
Difference Between String and Literal in Python?
14.
Frequently Asked Questions
14.1.
What is an example of a literal in Python?
14.2.
What are the 3 literals in Python?
14.3.
What is the literal 1 in Python?
14.4.
What are two examples of literals?
14.5.
What is the difference between a literal and a datatype in Python?
15.
Conclusion
Last Updated: Oct 9, 2024
Easy

Literals in Python

Author Tashmit
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

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

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 are - 

  1. Numeric Literals in Python
     
  2. String Literals in Python
     
  3. Boolean Literals in Python
     
  4. Literal Collection 
     
  5. Special Literals in Python
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.

Integer

In Python, an integer (int) is a data type used to represent whole numbers, both positive and negative, without any fractional part. Python's int type is of arbitrary precision, meaning it can grow as large as the memory allows.

number = 100  # This stores the whole number 100

Float 

A float in Python is a data type used to store decimal (floating-point) numbers. It can represent numbers with a fractional part or numbers that have a decimal point. Floats are stored using double precision and typically require 8 bytes of memory.

decimal_number = 10.56  # This stores the decimal number 10.56

Long

In Python 2, the long type was used for larger integer values that exceeded the limits of int. However, in Python 3, int can handle arbitrarily large numbers, and the long type has been integrated into the int type. Therefore, there is no separate long type in Python 3.

large_number = 1000000000000  # Python 3 can handle large integers like this without needing a 'long' type

Decimal Values

In Python, the decimal module provides support for fast and precise decimal floating-point arithmetic. This is especially useful when exact precision is needed (e.g., in financial applications) to avoid rounding errors common with float.

To use the decimal data type, you need to import the decimal module. It allows for arbitrary precision when performing arithmetic operations.

from decimal import Decimal
precise_decimal = Decimal('3.14159265359')  # This stores a more precise decimal value

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

  • Python

Python

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)
You can also try this code with Online Python Compiler
Run Code


The output of this code will be:

Output

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

Implementation

  • Python

Python

num1 =18.5
num2 =87.3
print(num1, num2)
You can also try this code with Online Python Compiler
Run Code

 

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. 

Single-line String

A single-line string is a sequence of characters enclosed in quotes and treated as a single line of text in programming. It typically does not span multiple lines and is used for straightforward text representation.

Let us see some examples.

  • Python

Python

str1 ="Coding Ninjas"
print(str1)
You can also try this code with Online Python Compiler
Run Code


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

Multi-line String

A multi-line string is a sequence of characters enclosed in triple quotes or specific delimiters that spans multiple lines, allowing for the representation of text blocks with line breaks and indentation in programming.

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

  • Python

Python

str1 ='''I
am
a
ninja'''
print(str1)
You can also try this code with Online Python Compiler
Run Code

 

The output of this code will be:

Output

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

Implementation

  • Python

Python

str2 ="\"I'm a coder!\""
print(str2)
You can also try this code with Online Python Compiler
Run Code

 

This will generate the following output:

Output

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

Implementation

  • Python

Python

str1 ="Welcome "
str2 ="to "
str3 ="Coding Ninjas!"
print(str1 + str2 + str3)
You can also try this code with Online Python Compiler
Run Code

 

This will generate the output as follows:

Output

3. 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

  • Python

Python

num =1605

if num >1000:
print("num is greater than 1000")
else:
print("num is less than or equal to 1000")
You can also try this code with Online Python Compiler
Run Code

 

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

  • Python

Python

a =True
b =False
c =a and b
d =a or b
print(c,d)
You can also try this code with Online Python Compiler
Run Code

 

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

4. 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

  • Python

Python

ninja_list =[16,25,"Python",3.629]
print(ninja_list)
You can also try this code with Online Python Compiler
Run Code

 

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

  • Python

Python

ninja_tuple =(16,25,"Coding Ninjas",True)
print(ninja_tuple)
You can also try this code with Online Python Compiler
Run Code

 

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

  • Python

Python

ninja_dict = {"Name": "Ninja1", "Age": 25, "Country": "India"}
print(ninja_dict)
You can also try this code with Online Python Compiler
Run Code

 

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

  • Python

Python

ninja_set ={1,2,3,4,5}
print(ninja_set)
You can also try this code with Online Python Compiler
Run Code

 

This will give output as:

Output

5. 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

  • Python

Python

ninja_var =None
if ninja_var is None:
print("ninja_var is not initialized")
else:
print("ninja_var is initialised")
You can also try this code with Online Python Compiler
Run Code

 

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.

Difference Between String and Literal in Python?

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

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!

Live masterclass