Python Datatypes

Python Datatype

Each variable in python has it’s own data type. Python is dynamically typed language, meaning we do not need to specify type explicitly. The type of the variable will depend on the value being stored in the variable. Python interpreter will automatically assign type to a variable. The datatypes are classes in python and the variable is object of a particular datatype.

We can use type()   function to determine which type of class a variable belongs to. 

For example,

x = 100     # variable of type int
y = 85.6    # variable of type float
z = "Mango" # variable of type string

print("type of x =",type(x))
print("type of y =",type(y))
print("type of z =",type(z))

 The output of above is,

type of x = <class 'int'>
type of y = <class 'float'>
type of z = <class 'str'>

Standard data type in python

Python stores data in various data types. For example, the name of an item should be stored in string variable where as its price in numeric value. Likewise a person’s name should be stored in string variable, whereas his/her salary in a numeric value. 

Python standard datatype consist of 4 types depending on categorization:

1. Numbers / numeric typeinteger, float, Complex Number
2. Sequence typeString, List, Tuple, Dictionary, Set
3. Boolean typeTrue, False
4. None typeNone

Among the above category, the most important datatypes (frequently used ones are):

1. Numbers

2. Strings

3. List 

4. Tuple

5. Dictionary

6. Set

Numbers/ Numeric datatype

The numeric data type consist of 3 types: integer, float ,and complex numbers. The data types are assigned when we assign value to a variable.

x = 90  # integer datatype
y = 3.14 # float datatype
z = 3+4.5j # complex datatype

print("type of x =",type(x))
print("type of y =",type(y))
print("type of z =",type(z))

Output:

type of x = <class 'int'>
type of y = <class 'float'>
type of z = <class 'complex'>

Sequence datatype

The sequence type is the datatype which we can loop through and generally consist of multiple items. The datatype String, List, Tuple, Dictionary, Set, Frozenset, and Range falls under this category.

String

Strings are sequence of multiple characters. We can use single or double quote ( ‘  ‘ or ”  ” ) to represent string. Multiple line of string can be represented by triple quotes (“””  “”” or ”’  ”’ ).

a = "hellow world! Single line string" # sinlge line string using ''
b = 'hellow world! Single line string' # single line string using ""
c = """hellow 
world ! 
Python is an awesome language. 
Multi-line string!
"""

d = '''hellow 
world ! 
Python is an awesome language.
Multi-line string
'''

print(a)
print("type of a =",type(a))

print(b)
print("type of b =",type(b))

print(c)
print("type of c =",type(c))

print(d)
print("type of d =",type(d))

The output of above program is,

hellow world! Single line string
type of a = <class 'str'>
hellow world! Single line string
type of b = <class 'str'>
hellow
world !
Python is an awesome language.
Multi-line string!

type of c = <class 'str'>
hellow
world !
Python is an awesome language.
Multi-line string

type of d = <class 'str'>

List

List  is an ordered sequence of items. The item in a list don’t need to be of same type. Declaring list is simple we put item in [ ] separated by commas(,). 

a = [1,'two',3.5]

The item in the list can be changed and can be accessed by list_name[index]   , index start with 0 and progresses in positive direction meaning
list_name[0] represents first element in the list, list_name[1], represent second element, list_name[2] represents third element and so on.

We can do various operation in list like changing element, extracting sub element list, deleting element.

a = [1,'two',3.5, 4,5,7]
print("original a = ",a)

# print single element
print("a[3]",a[3])

# change 2nd index element 
a[1] = 2
print("changed list a=",a)

sub_list =  a[3:5] # Extracting sub element, new list will have 4th and 5th element= [4,5]
print("new sub list ",sub_list)

# delete element using del keyword
del a[2]
print("updated list by deleting 3rd element=",a)

The output of above program is,

original a =  [1, 'two', 3.5, 4, 5, 7]
a[3] 4
changed list a= [1, 2, 3.5, 4, 5, 7]
new sub list  [4, 5]
updated list by deleting 3rd element= [1, 2, 4, 5, 7]    

Dictionary 

A dictionary is a collection of unordered items having key and value. The key and value can be of any type. In collection of multiple items inside a dictionary the key must be unique, however, value may not be unique. 
A dictionary is created using curly braces ( { }  ) . 

syntax:

dict_name={
    'key1':'value1',
    'key2':'value2'
}

For example:

Simple example

d={
    'name':'Bhoj',
    'surname':'karki',
}

Mixed type dictionary.

d = {
    1:"Item",
    "key":33,
    4.5: 2,
    4+5j:55,
    }
# accessing elements
print(d[1])
print(d["key"])
print(d[4.5])
print(d[4+5j])

The output of above program is. 

Item
33
2
55

We can use anything in value part, however, we need to pay attention with the key, key must be unique, meaning a dictionary can not have item pairs with same key. Also it is always a good practice to use either integer value or string value to represent key. You can use any data type in key like integer, float, complex number, string, boolean type or even bytes array. However a good practice it to use integer and string in the key portion.

We can access elements using its key as index, similar to list. We can not use 0,1,2,3,etc as index until and unless these value represent the  key in the dictionary. We strictly have to use key in the index to access them. Also, dictionary is mutable, meaning its values can be changed.

Example:

d = {
    'team':'A1',
    'score':5
}

# accessing element using dictionary_name[key]
print("d['team']=",d['team'])
print("d['score']=",d['score'])

# changing element using dict_name[key]= value
d['team'] = 'new team'
# print the new dict
print("d=",d)

The output of above program is,

d['team']= A1
d['score']= 5
d= {'team': 'new team', 'score': 5}

Tuple

A tuple is an ordered sequence of items same as list. However, the items are immutable, meaning once defined they can not be altered. The tuples are generally used to store data where we do not want the item to change. 

A tuple is defined using round bracket , ( ) .  If we assign multiple item separated by comma , then those also create a tuple.    

For example.

t1 = (1,'two',3)  # this is a tuple
print("type of t1=",type(t1))

t2 = 1,2,3,'four',6.6 # this is also a tuple
print("type of t2=",type(t2))

The output of above program is,

type of t1= <class 'tuple'>
type of t2= <class 'tuple'>

Since tuple can only be accessed once created, trying to change tuple will cause an error. The items in tuple are accessed using 0,1,2,..N index numbers similar to list.

t = (1,2,3)
print(t[1])

t[1]=5 # error 

Output

2
Traceback (most recent call last):
  File "d:\PythonSparkContent\python_tutorial_basic1.py", line 121, in <module>
    t[1]=5 # error
TypeError: 'tuple' object does not support item assignment

Set

Set is a collection of unordered items. The difference between set and a list is set has unique element, meaning if we have duplicate item set will automatically store unique item. This is often the reasons set is also used when we want to get only unique item in list. 
A set is defined using curly brackets ( { } ). The items are separated by comma. We separate dictionary and set by (key,value) pair, if we define (key,value) inside the curly braces it forms dictionary, if we use only single item separated by comma inside curly bracket it forms set. 

For example:

s = {1,2,3,'four',5.5}
print("type of s=",type(s))

Output:

type of s= <class 'set'>

Sets are not ordered, therefore accessing member using slicing i.e. set_name[index] operation will throw an error, like wise changing element is also not permissible using slicing operator

For example:

s = {1,2,3,'four',5.5} 
print("s[0]=",s[0]) # will throw error

output:

Traceback (most recent call last):
  File "d:\PythonSparkContent\python_tutorial_basic1.py", line 129, in <module>
    print("s[0]=",s[0]) # will throw error
TypeError: 'set' object is not subscriptable

Likewise since set can only have unique item. If a set is defined with duplicate items the set will remove duplicate items and only keep unique items.

For example,

# set can not have duplicate items
s1 = {1,1,1,2,2,2,3,4}
print('s1=',s1) # it will only have {1,2,3,4}

Output

s1= {1, 2, 3, 4}

Boolean datatype

We have two boolean values True and False . These values are generally use to set values where the outcome will surely happen or not happen at all. For example. 

isPlayerActive = True
willYouGiveExamAgain = False

print("type of isPlayerActive=",type(isPlayerActive))
print("type of willYouGiveExamAgain=",type(willYouGiveExamAgain))

Output:

type of isPlayerActive= <class 'bool'>
type of willYouGiveExamAgain= <class 'bool'>

Note: in python generally 0(zero) is treated as False and 1 is treated as True.

For example

# will be true
print("is 0 equals False", 0==False)
print('is 1 equals True=', 1 == True)

# will be false
print('is 0 equals True=',0==True)
print('is 1 equals False=',1==False)

output:

is 0 equals False True
is 1 equals True= True
is 0 equals True= False
is 1 equals False= False

None Type

The none type defines nothing or empty value. For example,

x = None
print(type(x))

output:

<class 'NoneType'>

Leave a Reply

Your email address will not be published. Required fields are marked *