 # Data Types in Python

Data Types in Python are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

Every value has its own python data type, in the python programming language. The classification of knowledge items or to place the info value into some kind of data category is named Data Types. It helps to know what quiet operations are often performed on a worth.

Data Type represents the type of data present inside a variable.

In Python we are not required to specify the type explicitly. Based on value provided, the type will be assigned automatically. Hence Python is dynamically Typed Language.

Python contains the following inbuilt data types

1) Int

2) Float

3) Complex

4) Bool

5) Str

6) Bytes

7) Bytearray

8) Range

9) List

10) Tuple

11) Set

12) Frozenset

13) Dict

14) None

Let see in details of each Data Types in Python.

## 1) int Data Type:

This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be.

We can use int data type to represent whole numbers (integral values)

Eg: a = 10

type(a) #int

In Python2 we have long data type to represent very large integral values.

But in Python3 there is no long type explicitly and we can represent long values also by using int type only.

We can represent int values in the following ways

1) Decimal form

2) Binary form

3) Octal form

4) Hexa decimal form

I) Decimal Form (Base-10):

It is the default number system in Python

The allowed digits are: 0 to 9

Eg: a =10

II) Binary Form (Base-2):

The allowed digits are : 0 & 1

Literal value should be prefixed with 0b or 0B

Eg: a = 0B1111

a = 0B123

a = b111

III) Octal Form (Base-8):

The allowed digits are : 0 to 7

Literal value should be prefixed with 0o or 0O.

Eg: a = 0o123

a = 0o786

IV) Hexa Decimal Form (Base-16):

The allowed digits are: 0 to 9, a-f (both lower and upper cases are allowed)

Literal value should be prefixed with 0x or 0X

Eg: a = 0XFACE

a = 0XBeef

a = 0XBeer

Being a programmer, we can specify literal values in decimal, binary, octal and hexa decimal forms. But PVM will always provide values only in decimal form.

• a=10
• b=0o10
• c=0X10
• d=0B10
• print(a)10
• print(b)8
• print(c)16
• print(d)2

### 2) Float Data Type:

This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.

The main advantage of exponential form is we can represent big values in less memory.

We can represent int values in decimal, binary, octal and hexa decimal forms. But we can represent float values only by using decimal form.

We can use float data type to represent floating point values (decimal values)

Eg: f = 1.234

type(f) float

### 3) Complex Data Type:

Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j

For Example:

c = 8+3j

print(c, “is a type”, type(c))

Output: (8+3j) is a type

3 + 5j

10 + 5.5j

0.5 + 0.1j

In the real part if we use int value then we can specify that either by decimal, octal, binary or hexa decimal form.

But imaginary part should be specified only by using decimal form.

We can use complex type generally in scientific Applications and electrical engineering Applications. Complex data type has some inbuilt attributes to retrieve the real part and imaginary part

c = 10.5+3.6j

c.real à 10.5

c.imag à 3.6

### 4) bool Data Type:

Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

Internally Python represents True as 1 and False as 0

a,b = True, False

type(a) bool

type(b) bool

True+True 2

True-False 1

### 5) str Data Type:

In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.

str represents String data type. A String is a sequence of characters enclosed within single quotes or double quotes.

s1=’Cloud’

s1=”Cloud”

Slicing of Strings:

1) slice means a piece

2) [ ] operator is called slice operator, which can be used to retrieve parts of String.

3) In Python Strings follows zero based index.

4) The index can be either +ve or -ve.

5) +ve index means forward direction from Left to Right

6) -ve index means backward direction from Right to Left

-5   -4 -3  -2    -1

 C L O U D

0      1    2     3      4

S à C

S[-5] àC

S[-6] à IndexError: string index out of range

### 6) bytes Data Type:

bytes data type represens a group of byte numbers just like an array.

The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any other values then we will get value error.

Once we creates bytes data type value, we cannot change its values, otherwise we will get TypeError.

 1) x = [10,20,30,40] 2) b = bytes(x) 3) type(b) à bytes 4) print(b) à 10 5) print(b[-1]) à 40 6) >>> for i in b : print(i) 7) 8) 10 9) 20 10) 30 11) 40

### 7) bytearray Data Type:

bytearray is exactly same as bytes data type except that its elements can be modified.

 1) x=[10,20,30,40] 2) b = bytearray(x) 3) for i in b : print(i) 4) 10 5) 20 6) 30 7) 40 8) b=100 9) for i in b: print(i) 10) 100 11) 20 12) 30 13) 40

### 8) List Data Type:

Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.

A list is formed(or created) by placing all the items (elements) inside square brackets [ ], separated by commas.

It can have any number of items and they may or may not be of different types (integer, float, string, etc.).

A list is mutable, which suggests we will modify the list

If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type.

1) Insertion Order is preserved

2) Heterogeneous Objects are allowed

3) Duplicates are allowed

4) Growable in nature

5) Values should be enclosed within square brackets.

 List1 = [3,8,7.2,”Hello”] print(“List1 = “, List) Output:  List1 = 7.2 print(“List1[1:3] = “, List[1:3]) Output: List1[1:3] = [8, 7.2]

list is growable in nature. i.e based on our requirement we can increase or decrease the size.

>>>List1.append(“CloudNClear”)

>>>List1

>>>[3.8.7.2,”Hello”, “CloudNClear”]

An ordered, mutable, heterogenous collection of eleemnts is nothing but list, where duplicates also allowed.

### 9) Tuple Data Type:

Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class. We can represent tuples using parentheses ( ).

tuple is the read only version of list

 1) t=(10,20,30,40) 2) type(t) 3) 4) t=100 5) TypeError: ‘tuple’ object does not support item assignment 6) >>> t.append(“durga”) 7) AttributeError: ‘tuple’ object has no attribute ‘append’ 8) >>> t.remove(10) 9) AttributeError: ‘tuple’ object has no attribute ‘remove’

### 10) Range Data Type:

range Data Type represents a sequence of numbers. The elements present in range Data type are not modifiable. i.e range Data type is immutable.

Examples:

range(10)

• generate numbers from 0 to 9
• for i in r : print(i) à 0 to 9

range(10, 20)

• generate numbers from 10 to 19
• for i in r : print(i) à10 to 19

range(10, 20, 2)

• 2 means increment value
• for i in r : print(i) à 10,12,14,16,18

### 11) set Data Type:

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.

If we want to represent a group of values without duplicates where order is not important then we should go for set Data Type.

1) Insertion order is not preserved

2) Duplicates are not allowed

3) Heterogeneous objects are allowed

4) Index concept is not applicable

5) It is mutable collection

6) Growable in nature

set is growable in nature, based on our requirement we can increase or decrease the size.

For Example:

Set = {4,3,6.6,”Hello”}

print(Set)

Output: {‘Hello’, 3, 4, 6.6}

### 12) frozenset Data Type:

It is exactly same as set except that it is immutable. Hence, we cannot use add or remove functions.

 1) >>> s={10,20,30,40} 2) >>> fs=frozenset(s) 3) >>> type(fs) 4) 5) >>> fs 6) frozenset({40, 10, 20, 30}) 7) >>> for i in fs:print(i) 8) … 9) 40 10) 10 11) 20 12) 30 13) 14) >>> fs.add(70) 15) AttributeError: ‘frozenset’ object has no attribute ‘add’ 16) >>> fs.remove(10) 17) AttributeError: ‘frozenset’ object has no attribute ‘remove’

### 13) dict Data Type:

In Python, Dictionary is an unordered collection of data values, which is used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, a Dictionary consists of key-value pair. Key-value is provided within the dictionary to form it more optimized. In the representation of a dictionary data type, each key-value pair during a Dictionary is separated by a colon: whereas each key’s separated by a ‘comma’.

If we want to represent a group of values as key-value pairs then we should go for dict data type.

Eg: d = {101:’Cloud’,102:’And’,103:’Clear’}

Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value.

dict is mutable and the order won’t be preserved.

### 14) None Data Type:

None means nothing or No value associated. If the value is not available, then to handle such type of cases None introduced. It is something like null value in Java.

Eg:

def m1():

a=10

print(m1())

None

These are the Data Types in Python. Lets discuss few in detail in next posts.

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

Python Exception Handling Using try, except and finally statement

File Handling in Python

Python Random module

Python reduce() Function

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)