Literals in Python with examples
Hello everyone, In this tutorial, we’ll be learning all about Literals and different types of Literals in Python with examples. Let us start this tutorial with a brief definition of Literals.
Literals in Python
Every data-type in Python is a class and to use them we need to initialize an object of that class like to use an integer no. in our code we have a class int, so to define something like ‘a’ will hold integer value 2, we have to do something like a = int(2). This is applicable to all such classes like float, complex, str, etc. many more. In every project, we need to use many such declarations, therefore it not very readable and is very tiring to initialize every time we need a variable that holds some value. To overcome this we have Literals, which is a very convenient way to make objects of these classes in our program. Taking the example above, we can simply write a=2. We will study more about them in the following sections.
Boolean Literals
Boolean Literals represents two expressions that are, True or False.
a = True b = False print((a+b),bool(a+b))
The output of the code above will be.
1 True
We are getting 1 as output because True+False means 1+0 that is equal to 1.
Numeric Literals
These are the Literals that are used to define values in digits or Numbers. Some of the Numeric Literals in Python are Int, Float, Complex, Octal, Hexadecimal.
c = 23 # Integer Literal d = 0o257 # Octal Literal e = 23.657787 # Floating Point Literal f = 23+5j # Complex Literal g = 0x18d # Hexadecimal Literal print("Value of c is ",c) print("Value of d is ",d) print("Value of e is ",e) print("Value of f is ",f.real,f.imag) print("Value of g is ",g)
Note: Octal and Hexadecimal notations will automatically print their corresponding decimal values.
Value of c is 23 Value of d is 175 Value of e is 23.657787 Value of f is 23.0 5.0 Value of g is 397
String Literals
A simple way to create the object of string class allowing us to make single-line or multi-line strings. In Python, there are many different types of Sring literals and we generally use single, double, triple quotes or their combination. See the example below to get an understanding of them.
h = 'CodeSpeedy - Coding Solution\n' i = "CodeSpeedy - Coding Solution &\n" j = "'CodeSpeedy' - Coding Solution & Software\n" k = '''CodeSpeedy - Coding Solution & Software Development\n''' l = "CodeSpeedy - \ Coding Solution & \ Software Development" print(h) print(i) print(j) print(k) print(l)
Read the code carefully & try to figure out what should be the output of the above program and compare it with the output we will be getting after running this code.
CodeSpeedy - Coding Solution CodeSpeedy - Coding Solution & 'CodeSpeedy' - Coding Solution & Software CodeSpeedy - Coding Solution & Software Development CodeSpeedy - Coding Solution & Software Development
Note –
- ”’__”’ (Triple quotes) will take everything as a string inside it, no matter how many new lines are there.
- We can also define a single long string in multiple lines using the backslash symbol at the end of each line as shown in the code above.
Special Literal in Python
Python has a special kind of literal known as None which simply means that a field has not been created. None is a pre-defined keyword but because it works as a literal also, therefore considered as a Special Literal.
m = None print(type(m),'\t',m)
<class 'NoneType'> None
Collection Literals in Python
The collection is made up of different types of primitive datatype objects that are grouped together to form a single entity. In Python, Collection includes List, Set, Tuple, and Dictionary, etc.
List
- The comma (,) separates each element in a list that is enclosed within square brackets ([]).
- Lists are mutable means that we can alter or modify the elements in a list if required.
n = ['Codespeedy',1,2+3j,0.038,"hello"] print("Type of n is ",type(n),"having values \n",n)
Type of n is <class 'list'> having value: ['Codespeedy', 1, (2+3j), 0.038, 'hello']
Set
- Sets are mutable.
- There is no Repetition of the elements in a set.
- They cannot be sliced like list, trying to do so will give an error like “set object is not subscriptable”.
- The comma (,) separates each element in a set that is enclosed within curly brackets ({}).
o = {'Codespeedy',1,2+3j,0.038,"hello"} print("Type of o is ",type(o),"having value: \n",o)
Type of o is <class 'set'> having value: {'Codespeedy', 1, 'hello', (2+3j), 0.038}
Dictionary
- Dictionaries are mutable.
- Elements in a dictionary exist in the form of key: value pairs and accessing them is easy.
- The comma (,) separates each key: value pair in a dictionary which is enclosed within curly brackets ({}).
p = {1:'CodeSpeedy',2:5, 6:(2+1j)} print("Type of p is ",type(p),"having value: \n",p) print(p.keys()) print(p.values())
Type of p is <class 'dict'> having value: {1: 'CodeSpeedy', 2: 5, 6: (2+1j)} dict_keys([1, 2, 6]) dict_values(['CodeSpeedy', 5, (2+1j)])
Tuple
- Similar to lists but are immutable means, we cannot alter or modify the elements in a tuple.
- The comma (,) separates each element in a tuple that is enclosed within Round brackets (()).
- Trying to reassign elements of tuples will give TypeError: ‘tuple’ object does not support item assignment error.
q = ('Codespeedy',1,2+3j,0.038,"hello") print("Type of q is ",type(q),"having value: \n",q)
Type of q is <class 'tuple'> having value: ('Codespeedy', 1, (2+3j), 0.038, 'hello')
We hope you like this tutorial and if you have any doubts or queries, feel free to leave a comment below.
You may like to read.
Leave a Reply