In the previous chapter, we had learned about variables. In this tutorial, we will discuss data types in Python language. In Python programming, data types are inbuilt and need not declare the type of a variable. Everything in Python is an object, so data types are classes and variables are known as an object.
Numeric Types – int, float, complex
Integer or int: Integers are whole numbers and can be of any length.
Float: Numeric value specified with a decimal point is known as float.
Complex Number: Complex numbers have a real and imaginary part, appending with ‘j’ or ‘J’.
a=10
b=3.14
c=1 + 2j
print(a)
print(b)
print(c)
type() – We can use type() function in python with one argument, to check the type of variable or object.
a=10
b=3.14
c=1 + 2j
print(type(a))
print(type(b))
print(type(c))
<class ‘int’>
<class ‘float’>
<class ‘complex’>
Boolean
Boolean: In Python, the boolean type may have True or False value. Capitalization of the first character is a must.
a=True
b=False
print(a)
print(b)
print(type(a))
print(type(b))
True
False
<class ‘bool’>
<class ‘bool’>
String
String: In Python, text values are stored as a string. It is a sequence of characters, delimited with single or double-quotes.
a='First String'
b="Second String"
print(a)
print(b)
print(type(a))
print(type(b))
First String
Second String
<class ‘str’>
<class ‘str’>
Sequence Data Type – list, tuple, range
List: lists are sequence type and may store the collection of different types of data, it is mutable.
Tuple: A tuple is similar to a list, but it is immutable.
Range: Range is also an immutable type and commonly used for looping.
#creating a list by placing all items inside a square bracket [ ].
n=[10,20,30]
print(n)
print(type(n))
#creating a tuple by placing all items inside a round bracket ( ).
n=(1,2,3)
print(n)
print(type(n))
#creating a range using function.
n=range(10)
print(n)
print(type(n))
Set Data Types – set, frozenset
Set: Set is a collection of unique and unordered objects. It is mutable and creates using a set() function.
Frozenset: Frozenset is also a collection of unique and unordered, but it is immutable. We can create it using a frozenset() function.
#creating a set, using set() function
x = set("abacda")
print(x)
print(type(x))
#creating a frozenset, using a frozenset() function
x = frozenset("abacda")
print(x)
print(type(x))
{‘b’, ‘c’, ‘d’, ‘a’}
<class ‘set’>
frozenset({‘b’, ‘c’, ‘d’, ‘a’})
<class ‘frozenset’>
Mapping Data Types – dict
dict: – A dictionary is an unordered and mutable collection of objects, and have keys and values. In Python, dictionaries are creating using curly brackets { }.
#creating a dictionary, having keys and values.
x = {"one":1,"two":2,"three":3}
print(x)
print(x.keys())
print(x.values())
print(type(x))
{‘three’: 3, ‘two’: 2, ‘one’: 1}
dict_keys([‘three’, ‘two’, ‘one’])
dict_values([3, 2, 1])
<class ‘dict’>