What is datatype in python?

datatype :-

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

There are various data types in Python.


File name : index.php

  • Numbers
  • List
  • Tuple
  • Strings
  • Set
  • Dictionary

  • Python Numbers

    Number data types store numeric values. Number objects are created when you assign a value to them.

    Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.

    File name : Example

    var1 = 2
    var2 = 7

    Note : We can use the type() function to know which class a variable or a value belongs to. Similarly, the isinstance() function is used to check if an object belongs to a particular class.

    File name : index.php

    x = 2
    print(x, "is of type", type(x))

    y = 2.0
    print(y, "is of type", type(y))

    z = 2+3j
    print(x, "is complex number?", isinstance(2+3j,complex))


    2 is of type <class 'int'>
    2.0 is of type <class 'float'>
    (2+3j) is complex number? True

    Integers can be of any length, it is only limited by the memory available. A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

    File name : index.php

    To initialize a variable with integer value, use assign operator and assign the integer value to the variable. Variable name has to be on the left hand side and the integer value has to be on the right side.
    x = 20
    y = 45

    print(x)
    print(y)

    a, b = 3, 4

    #addition
    print(a+b)

    #subtraction
    print(a-b)

    #multiplication
    print(a*b)

    Python Complex Number:-

    Python supports complex numbers and has a datatype called complex. A complex number contains a real part and imaginary part.

    We can initialize a complex number in two ways. The first process is using complex() function. The second is initializing the variable with the actual complex number.

    File name : index.php

    cn = complex(5,6)
    print(cn)

    cn = 5 + 6j
    print(cn)

    output :-

    (5+6j)
    (5+6j)
    where 5 is the real part and 6 is the imaginary part.

    complex() function takes real part and imaginary part as arguments respectively. While assigning the actual complex number to a variable, we have to mention j next to the imaginary part to tell Python that this is the imaginary part.

    File name : index.php


    Python Complex Number – type()

    File name : index.php

    cn = 5 + 6j

    print(cn)
    print(type(cn))

    Output:-
    (5+6j)
    <class 'complex'>

    File name : index.php


    Python List

    List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
    A list contains items separated by commas and enclosed within square brackets [ ].

    File name : index.php

    a = [2, 3.2, 'sana']
    We can use the slicing operator [ ] to extract an item or a range of items from a list. The index starts from 0 in Python.

    List Example

    File name : index.php

    x = [5,10,15,20,25,30,35,40]

    # x[2] = 15
    print("x[2] = ", x[2])

    # x[0:3] = [5, 10, 15]
    print("x[0:3] = ", x[0:3])

    # x[5:] = [30, 35, 40]
    print("x[5:] = ", x[5:])

    Output:
    a[2] = 15
    a[0:3] = [5, 10, 15]
    a[5:] = [30, 35, 40]

    Note :

    Lists are mutable, meaning, the value of elements of a list can be altered.

    a = [1, 2, 3]
    a[2] = 4
    print(a)

    The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

    list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
    tinylist = [123, 'john']

    print list # Prints complete list
    print list[0] # Prints first element of the list
    print list[1:3] # Prints elements starting from 2nd till 3rd
    print list[2:] # Prints elements starting from 3rd element
    print tinylist * 2 # Prints list two times
    print list + tinylist # Prints concatenated lists


    Output :
    ['abcd', 786, 2.23, 'john', 70.2]
    abcd
    [786, 2.23]
    [2.23, 'john', 70.2]
    [123, 'john', 123, 'john']
    ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

    Python Tuples

    Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically. It is defined within parentheses () where items are separated by commas.

    A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

    The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

    We can use the slicing operator [] to extract items but we cannot change its value.

    File name : index.php

    t = (5,'program', 1+3j)

    # t[1] = 'program'
    print("t[1] = ", t[1])

    # t[0:3] = (5, 'program', (1+3j))
    print("t[0:3] = ", t[0:3])

    # Generates error
    # Tuples are immutable
    t[0] = 10

    output:
    t[1] = program
    t[0:3] = (5, 'program', (1+3j))
    Traceback (most recent call last):
    File "test.py", line 11, in <module>
    t[0] = 10
    TypeError: 'tuple' object does not support item assignment

    Python Strings

    Python String is an immutable sequence of unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """

    In string handling, the + operator is used to concatenate two strings as the operation "sana"+" mahtab" returns "sana mahtab".

    File name : index.php

    str = "Hello Sana Mahtab"
    print(str)
    s = '''''Welcome
    Sana & Sara'''
    print(s)

    File name : index.php

    str1 = 'hello sanamahtab' #string str1
    str2 = ' how are you' #string str2
    print (str1[0:2]) #printing first two character using slice operator
    print (str1[4]) #printing 4th character of the string
    print (str1*2) #printing the string twice
    print (str1 + str2) #printing the concatenation of str1 and str2

    To define a string literal, you can use single quotes, double quotes or triple quoted.

    File name : index.py

    str1 = 'hello world!' #single quotes
    str2 = "hello world!" #double quotes
    str3 = """hello world!""" #triple quoted with double quotes
    str4 = '''hello world!''' #triple quoted with single quotes

    Triple quoted strings can define multiple line strings.

    File name : index.py

    str1 = '''hello world!
    hello user!
    hello!'''

    Python str type

    File name : index.py

    greeting = 'hello world!'
    print(type(greeting))
    output :-

    Convert to String

    To convert objects of other datatype to string, you can use str() function.

    File name : index.py

    n = 25.95236
    str1 = str(n)
    print(str1)

    File name : index.py

    str1 = 'hello'
    for char in str1:
    print(char)

    Python Set

    Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.

    Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values.

    File name : index.py

    a = {5,2,3,1,4}

    # printing set variable
    print("a = ", a)

    # data type of variable a
    print(type(a))

    Example

    File name : index.py

    # Creating Empty set
    set1 = set()

    set2 = {'James', 2, 3,'Python'}

    #Printing Set value
    print(set2)

    # Adding element to the set

    set2.add(10)
    print(set2)

    #Removing element from the set
    set2.remove(2)
    print(set2)

    Output :-

    {3, 'Python', 'James', 2}
    {'Python', 'James', 3, 2, 10}
    {'Python', 'James', 3, 10}

    Python Dictionary

    Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.

    Key can hold any primitive data type, whereas value is an arbitrary Python object. The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

    File name : index.py

    d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

    # Printing dictionary
    print (d)

    # Accesing value using keys
    print("1st name is "+d[1])
    print("2nd name is "+ d[4])

    print (d.keys())
    print (d.values())

    Output :-

    1st name is Jimmy
    2nd name is mike
    {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
    dict_keys([1, 2, 3, 4])
    dict_values(['Jimmy', 'Alex', 'john', 'mike'])





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here