A Comprehensive List of the Different Python Data Types

Aashish Garg 19 Sep, 2022 • 11 min read

Introduction

Python is one of the most preferred programming languages these days. It allows developers to focus all their efforts on implementation instead of complex programs and data types in python are used for that purpose only to make our work easy.

Data Type in Python

 

Overview of the Different Data Types

The classification or categorization of data items is known as Data types. A kind of value is signified by data type which determines what operations need to be performed on that particular data.

  1. Int

    It is used for integral values. In python 2 versions, there was different Int and long for small and big integral values, but from python 3 it is int only.

    We can represent int in 4 forms.

    1. Decimal form ( it is by default and digits are from 0-9)
    2. Binary form (base-2, 0, and 1)a=1111, so if do print (a)It will be a normal decimal.So to convert it into binary, we make a change like a=0B1111So basically zero(0) small “ b” or zero(0) capital” B” is used in prefix.
    3. Octal form (0-7 )So in this zero(0) and capital “0” or small “o” is used in prefix.
    4. Hexadecimal (0-9, A-F)In this zero(0) and small or capital “x” is used.

Now the thing to remember is by default the answer we will get will be in decimal forms, so we can change that as well.

    • For converting into binary we will do : bin(15) -.> 0b1111
    • For converting into octal : oct(100) -> 0o144
    • For converting into hexadecimal : hex (1000) -> 0x3e8
  1. Float:

    Float is a data type in which decimal values are there. In float, we can only have decimal no binary, oct, or hex. Eg: a=15.5 So when we see the type of “a” It will be float type.

  2. Complex :

    A+bj – > Complex Number
    Eg:
    x=10+20j
    Print (type(x)) #so it will be complex

    Where j^2=-1
    Or imaginary
    J can be in caps or small, it doesn’t matter.
    print(x.real) – > 10.0
    print(x.imag)->=20.0

    The real part can be binary, octal, or hex anything, but the image should be decimal only.

    We can also take float values as well x=10.5+20.1j
    We can type real part in any form like binary octal or hexadecimal but not for imaginary

    OB111 + 20j  it is correct. But 14+ 0B101   it is incorrect

    Also if we have two complex numbers we can perform an arithmetic operation on them. Like if we have x= 10+20j and y=24+21j.
    So we can do x+y, we can do x*y  or we can do x/y  or x-y

    So addition or subtraction of the complex numbers is simple. We simply do addition or subtraction of the real part of both numbers and imaginary parts of both numbers.

    Now comes the multiplication part –
    (a+bi)  * (c+di)   = (ac-bd) + (ad+bc)i

    So whenever we multiply two complex numbers the answer we will get is by this formulae Or we have actually simplified the formula.

    Simply let’s say we take two complex numbers.

    a= (2 + 4j)       ,      b=  (10 + 10 j)

    So now when we multiply them It will be multiplied like this-– 2 (10 + 10j) + 4j(10+10j)

    20 + 20j  + 40j + 40j^2

    And we know ^2 of imaginary part is -1. So it will become-

    -20 + 60j

    And now comes the division part of the complex numbers.Let say we have two complex numbers
    a= p+qj

    b= r+sj

    So division would be

    a/b  =   pr + qs     +    qr – ps      ,  x= under root of (r^2 + s^2)

    ———          ——–

    X                    x

    This complex is used much in machine learning or mathematics specific queries.

  3. Boolean

    In boolean we have the answers in the form of  True or False.
    But one thing is to remember that the first letters should be in the capital True, False

    a=True
    Type (a)

    It will show bool

    So let’s take an example.

    it will show false

    The type would be

    Print (type(c))

    Bool

    Now one more thing to remember is True =1 and False =0

    So if we print (True + True)

    The answer would be 2 (1+1)

    And if we print (True-False) The answer would be 1  (1-0)

  4. Strings

    So in string data type, we can use single, double, or triple quotes. So for eg: S= ”Aashish”

    S=’Aashish’

    We can print type(s) it will give us string

    Also s = ”a”

    It will also give string unlike java etc because in java etc it must have given it as a character. but there is no data type as a character in python

    Now comes the triple quotes. If we have to write the string in multiple lines, then we cannot use single or double quotes, what we can use is single triple quotes or double triple quotes

    Like eg :

    s= ‘’’ My
    Name
    Is
    Aashish’’’

    Or

    s= “”” My
    Name
    Is
    Aashish”””

    One more thing we need to know now is the let say we have one statement. Like-

    s= Aashish is a very ‘good’ boy

    Now in the above statement if we want that Good should be in quotes, so while writing the string we should know that the statement should not be in single quotes. Like-

    “Aashish is a very ‘good’ boy”.

    And the same goes if we want something in double-quotes, then we have to make the whole statement in a single quote. Now if we want to use both single and double quotes in a statement.

    “Aashish” is a very ‘good’ boy

    Then we have to put the whole statement in triple quotes.

    Positive and Negative Index in strings

    So there is indexing in python string, so if let say we want to access the character of the word for eg: from a=  Aashish, we want to access “i”

    So we can do it like-

    Print (a[4])

    The first alphabet is represented by 0. Also, we can do like in python a[-1], which represents the last character.

    So it will print h

    Slice Operator in String: basically it’s a part of the string which is known as a slice. So to fetch that slice we use it.

    Eg:  “Aashish”

    In slicing let say we want only “shis”

    format is s[begin : end]

    Which returns from beginning to end-1. So if let’s say put s[2:6]. It will return to the 5th. Now if we are not specifying begin. Then it will start at 0 s[:5].

    If are not specifying it will continue to the end s[2:]. And one case is s[:]. It will return the total string.

    In one more case, we have still only 6. And let say we do s[3:1000]. So we will not get error, instead, we will get to the end of the string.
    One more case s[5:2]. We will get an empty string, as it cannot move from 5 to 2.

    Now let say we have a string s=”aashish”
    And we want the output as “Aashish”

    So we can do it like.

    output= s[0].upper() + s[1:]
    print(output)

    And let say we want s=”aashisH”
    So we can do it like

     

    output = s[0:len(s)-1]  + s[-1].upper()
    Print (output)

    Now let’s say we need to have the first character in the capital and the last character in the capital and remaining as it is. So what we need to do is simply :

    Output = s[0].upper() + s[1:len(s)-1] + s[-1].upper()
    Print (output )

     

    • And * operator for string data type :

     

    • Is used for concatenation, and both the arguments should be string only.

    So  it can be “String” + “String” + “string” + …..

    It cannot be like “String” + “Int”

    Now * operator

    s=”SUN” *3

    So it is a string repetition operator. And used to multiply the string. One thing to notice here is one argument should be a string and the other should be an integer

 

TypeCasting

The process of converting from one type to another type. 5 inbuilt functions are there-

  1. Int
  2. Float
  3. Complex
  4. bool()
  5. str()

 

  1. Int: To convert from other types to the int type

    1. Float to the int function, so like if we have 10.989 is there, so after the decimal point all digits will be gone so it will be done like int(10.989), it will give 10.
    2. Complex to int: 10+ 20j, so int (10+20j), it will give type error, as we cannot convert complex to int type.
    3. Bool to int:  int (True)   will give 1
    4. String to int :String internally contains an only integral value or in base 10 only, so no hexadecimal or binary, etc.Therefore int(“15”)  will give 15.Int (0B1111) will give an error

      int(“10.5”) , again error as it is not integral value it is a float value.

  2. Float: Convert into the float type

    Int to float:  float (15) answer will be 15.0
    Or float(0B1111) will give 15.0
    Or Float(0XFace) will give 64206.0

    Complex to float is not possible :

    Bool to float is possible
    If we convert float like
    float(True), then the answer would be 1.0
    float(False), then the answer would be 0.0

    String to float type is also possible, only in the case when the string contains an integral value or float value but they should be specified in base 10.

    Float (10)  will give 10.0

    Float (0XFACE)  error

    Float (“Aashish”) error

  3. Complex Type

    Complex (x)

    If only one argument then it will become a real value

    Complex (10)

    The answer would be 10 + 0j

    Complex (0B1111)  would be 15+0j

    Complex (10.5) would be 10.5 + 0j

    Complex (True) would be 1+0j

    Complex (False) would be 0j

    Complex (“String”) it should have either int or float value in base 10

    Complex (x,y)

    When two arguments are there one will go to real and one to the imaginary complex(10, 20) would be 10+20j.

    Complex (10.5, 20.6) would be 10.5 + 20.6j

    Complex (“10”, “20”)

    It will give an error if we are having the string argument, we can’t have the second value as a string as well

    Complex (10, “20”)

    It will also give an error, the second argument can’t be a string in complex

  4. Bool()

    Int argument
    bool(10)

    If the argument is 0 , then it will be false whether it is int, float, complex, etc.
    If it is non zero then it will be True

    Int
    bool(10) will give True

    bool(0) will give false

    Float

    bool(0.0) false
    bool(0.1) true

    Complex
    bool(0+0j)    False

    bool(1+0j)  True

    String

    bool(“True”)   True

    bool(“False”)   True

    bool(“Yes”)  True

    bool (“No”)   True

    bool( “ ”)   False

    If the string is empty then only it is false, otherwise if it not empty then it will be True

  5. String

    str(10)  “10”

    str(0B1111) “15”

    str(10.5)    “10.5”

    str(10+20j)  “10+20j”

    str(True)   “True”

    str(False)  “False”

     

Fundamental Data Types vs Immutability

  • Mutable  — > we can change
  • Immutable → we cannot change

Once we create an object, we cannot perform any changes in that object. If we try to change, then the new object would be created. This non-changeable behavior is immutability.

 

Python Data Type: Lists

These are the collection related data type.

l=[07, “Aashish”, 20,30, “Nimish”]
Print type(l)

It will give a list. The list is always in square brackets. If we print (l), the order will be in the same in which we have given. So the order of perseverance is there. Duplicates objects are allowed.

Heterogenous objects are allowed, like int, string, etc. Indexing and slicing are applicable. Now,

 print (l[0])

So will give the first element. And similarly -1 for the last. Now if let say we have an empty list.

l=[  ]

So we can add elements like-

l.append(10)

We can remove elements like-

l.remove(10)

Now let say, we have-

 l=[10, 20, 30, 40]

Now the list is mutable so at l[0] we can add value. Like-

 l[0]= 100

So now 100 will be added to the starting. List will become l[100, 10, 20, 30, 40].

 

Python Data Type: Tuple

Now we will learn the data type Tuple. It is the same as the list except it is immutable, if we create one object so we cannot add or remove any object or value. It is like a read-only version of a list. We represent tuple by (10, 20,”aashish”).

Performance is better than the list. And it also uses less memory than a list.

 

Python Data Type: Set

Now we will learn about the new data type i.e Set. It is used for the group of objects or entities but duplicates are not allowed and I don’t care about the order. So if we have such a type of requirement then we go for the Set.

So-

s1 = {1,2,3}
s2 = {3,1,2}

So basically s1 and s2 are equal. So in the set, there is no first element no last element kind of concept. Curly brackets are used inset.

s= {10, 10, 20, “Aashish”, 30}

But output will come s= {10, 20, “Aashish”, 30}

But order can be anything. So indexing cannot be there or slice operator-

Print s[0]

Will give an error.

Heterogeneous objects are allowed.

s.add(50)

In the list, it was appended. In set, it is added.

 

Append vs add

Append was used in the list to add items in the last. So add is used in the set, as we don’t know where it is going to get added.

s= {   }

So it is not known as an empty set it is known as an empty dictionary. As the dictionary gets privilege because of the frequent use of it more than the set.

If we want to create the empty set then we can create it like

s= set()

 

Python Data Type: Frozen set

It is exactly like a set except it is immutable. Because inset we can make changes, but not in the frozen set. So we create the frozen set like-

s={ 10, 20, 30, 40}
fr= frozenset(s)
Print type(fr)

It will be frozen set s.

So now we cannot add or remove the values from the frozen set and will get the attribute error if we try to do that.

 

Python Data Type: Range

Now we will learn about the Range.

R = range(10)

So we will get 10 values starting from the 0. So basically it is an inbuilt function used in python. If we print r-

It will give 0,1,2,3,4,5,6,7,8,9

We can use it like

For x in r :
   print(x)

So we will get all the values printed. How we can make the range objects.

Form:   range (n)

So will give values to 0 to n-1

Form :  range(begin : end)

So will give values from the beginning to the n-1

r= range(1, 10)
For x in r :
    Print (x)

So we will get 1,2,3 ….  9

Form:

Range (begin, end, increment/Decrement)

R = range(1,21,1)
So 1 to 20

1,2,3,….. 20

R = Range(1, 21,2 )

1,3,5… 19

Also, we can do like for decrement

Range (20, 1, -2)

So 20, 18 ….

So now we have known things go in order in range, so wherever order is there, we can do the indexing or slicing. But the range is immutable, as the values are in sequence and if we try to add the values, an error will occur.

 

Python Data Type: Dict

Now we will learn about the dictionary. Dictionary is different from the above data types in the manner that it is used to represent the key values.  Represent by Dict

d={ k1: v1, k2 : V2}

So let say we have an empty dictionary

d= {   }

So we can add value like

d[100]=”Aashish”
d[200]= “Ayush”

So it will look like-

{ 100 : Aashish , 200 : Ayush}

Now there would be one concern about the duplicity of the values. So duplicate keys are not allowed but values can be duplicated. S-

d[100]  = “Abhishek”

So the old value i.e Aashish will be replaced by the Abhishek, so the duplicate key is not allowed, anyhow there would be no error, but the value will get replaced by the new value.

No order there, similarly like a set. Heterogeneous values can be there. It is mutable, we can make changes. Slicing, indexing, etc are not there, due to no order.

 

Python Data Type: Bytes and BytesArray

l= [10, 20,30,40]

Till now it is a list. Now to convert it into the bytes we need to

Do-

b=bytes(l)

print(b)

Now It is used for the binary creation of the data. Bytes can only have values from 0 to 256. So basically if we add the value 256, 257 …

We will get the value error. Now in this as well indexing, slicing is there. But it is immutable, we cannot change its content. We will get an error. But if we want mutable bytes then it is known as Bytearray

l= [ 10, 20, 30, 40 ]
b=bytearray(l)
b[0]= 77
print(b[0])

 

None Data Type

None data type is nothing i.e no value is associated with it. To make the value available for the garbage collection-

a=None

None is also stored as object internally-

Print (type(a))

 

Escape Characters,  Comments, and Constants :

These are –

\ n  :   for the next line

\ t   :  for the tab space

\ r   : carriage return, means starting from the starting

\  b : backspace

\ f : form feed

\ ‘ : for single quote

\ “ : for double quote

\\ :   for backslash symbol

 

Now to type the comments in python :

// This is a single line comment

# This is a single line comment

So to type multi-line comments

We need to put # in every line.

 

Constants :

The things of which we cannot change the values

So as such no constant concept is there in python, but if we want the value to be constantly put it in the upper case.

MAX_VALUE=10

For the convention purpose only.

 

End Notes

So we learned that Datatypes are an important concept because statistical methods and certain other things can only be used with a certain python data type. You have to analyze data differently and then categorize data otherwise it would result in a wrong analysis.

Aashish Garg 19 Sep 2022

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Mahi
Mahi 31 Oct, 2020

Each and every part you have explained is quite clear... very well written

Abhishek
Abhishek 02 Nov, 2020

Every python lover must read this.. Aashish sir you are doing a great job ...thankyou for enhancing our knowledge on Python.

Sneha
Sneha 02 Nov, 2020

Very nice...

Python
Become a full stack data scientist