Data Types in Python

Spread the love

A data type represents the type of data stored into a variable or memory. The data types which are already available in Python language are called Built-in data types. The data types which can be created by the programmers are called user-defined data types.

Built-in Data Types –

The built-in data types are of five types.

  1. None Type
  2. Numeric Type
  3. Sequences
  4. Sets
  5. Mappings

1 . None Type –

In Python, the None data type represents an object that does not contain any value. In languages like java it is called ‘null’ object. But in Python it is called None object.

One of the uses of None is that it is used inside a function as a default value of the arguments. When calling a function, if no value is passed, then the default value will be taken as None. If some value is passed to the function then that value is used by the function. In Boolean expression, None data type represents False.

2 . Numeric Types –

The numeric types represents numbers. There are three sub types.

a . int

b. float

c. complex

Int data type –

The int data type represents an integer number. An integer number is a number without any decimal point or fraction part. For example 100, -25, 0, 5000 etc. are treated as integer numbers.

Now let’s store an integer number 100 into a variable a.

In [1]: a = 100

Here a is called int type variable since it is storing 100 which is an integer value.

float data Type –

The float data type represents floating point numbers. A floating point number is a number that contains a decimal point. For example 0.5, -3.4, 150.85, 0.001 etc are called floating point numbers.

Let’s store a float number into a variable b.

In [2]: b = 3.14

Here b is called float type variable since it is storing floating point value. Floating point numbers can also be written in scientific notation where we use ‘e’ or ‘E’ to represents the power of 10. Here e or E represents exponentiation. For example, the number 2.5 * 10**4 is written as 2.5E4.

In [3]: c = 2.5e4

Complex data type –

A complex number is a number that is written in the form of a + bj or a + bJ. Here ‘a’ represents the real part of the number and ‘b’ represents the imaginary part of the number. The suffix ‘j’, or ‘J’ after ‘b’ indicates the square root value of -1. The parts a and b may contain integers or floats. For example 3+5j, -1-5.5j, 0.2+10.5j are all complex numbers.

In [4]: d = -1-5.5j

Here the complex number -1-5.5j is assigned to the variable d. Hence python interpreter takes the data type of this variable as complex type.

3. bool data type –

The bool data type in Python represents boolean values. There are only two boolean values True or False that can be represented by this data type. Python internally represents True as 1 and False as 0. A blank string like “” is also represented as False. Conditions will be evaluated internally to either True or False.

For example

In [5]: a = 10

In [6]: b = 20

In [7]: if (a < b):
   ...:     print('Hello')

In the previous code, the condition a<b which is written after if is evaluated to True and hence it will execute print(‘Hello’).

4. Sequences in Python –

Generally a sequence represents a group of elements or items. For example a group of integer numbers will form a sequence. There are six type of sequences in Python.

  1. str
  2. bytes
  3. bytearray
  4. list
  5. tuple
  6. range

str data type –

In python str represents string data type. A string is represented by a group of characters. Strings are enclosed in single quotes or double quotes. Both are valid.

In [8]: a = 'welcome'

In [9]: a = "welcome"

We can also write strings inside “”” (triple double quotes) or ”’ (triple single quotes) to span a group of lines including spaces.

In [10]: str1 = """
    ...: This is a program to train a linear regression
    ...: model in scikit-learn. The goal is to predict
    ...: the housing prices.
    ...: """

In [11]: str2 = '''
    ...: This is a program to train a linear regression
    ...: model in scikit-learn. The goal is to predict
    ...: the housing prices.
    ...: '''

byte data type –

The bytes data type represents a group of byte numbers just like an array does. A byte number is any positive integer from 0 to 255(inclusive). byte array can store numbers in range from 0 to 255 and it cannot store negative numbers.

For example –

In [12]: elements = [10, 20, 0, 40, 15]

In [13]: x = bytes(elements)

In [14]: x[0]
Out[14]: 10

The second line in the above code convert the list into bytes array. We can not modify or edit any element in the bytes type array. For example x[0] = 55 gives an error. Here we are trying to replace 0th element (i.e. 10) by 55 which is not allowed.

bytearray data type –

The bytearray data type is similar to bytes data types. The difference is that the bytes type array cannot be modified but the bytearray type array can be modified. To create a bytearray type array, we can use the function bytearray as

In [15]: elements = [10, 20, 0, 40, 15]

In [16]: x = bytearray(elements)

In [17]: x[0]
Out[17]: 10

We can modify or edit the elements of the bytearray. For example we can write

In [18]: x[0] = 90

In [19]: x[1] = 80

Here we replaced the 0th element with 90 and 1st element with 80.

list data type –

Lists in Python are similar to arrays in C or Java. A list represents a group of elements. The main difference between a list and an array is that a list can store different types of elements but an array can store only one type of elements. Also list can grow dynamically in memory. But the size of array is fixed and they can not grow at runtime. Lists are represented using square brackets [] and the elements are written inside the [] separated by commas.

For example

In [20]: a_list = [100, -25, 'Max', 3.14]

The above code will create a list with different types of elements.

tuple data type –

A tuple is similar to a list. A tuple contains a group of elements which can be different type. The elements in the tuple is separated by commas and enclosed in parentheses (). whereas the list elements can be modified, it is not possible to modify the tuple elements. That means a tuple can be treated as a read only list.

Let’s create a tuple

In [21]: a_tuple = (100, -25, 'Max', 3.14)

range data type –

The range data types represents a sequence of numbers. The numbers in the range are not modifiable. Generally, range is used for repeating a for loop for a specific number of times. To create a range of numbers we can simple write.

In [22]: r = range(10)

Here, the range object is created with the numbers starting from 0 to 9. We can display these numbers using a for loop as

In [23]: for item in r:
    ...:     print(item)

In [24]: 

The above statement will display numbers from 0 to 9. We can use a starting number, and ending number and a step value in the range object as

In [25]: r = range(2, 22, 2)

This will create a range object with a starting number 2 and an ending number 20. The step size is 2. It means the numbers in the range will increase by 2 every time.

In [26]: for item in r:
    ...:     print(item)

In [27]: 

5 . Sets –

A set is an unordered collection of elements much like a set in Mathematics. The order of elements is not maintained in the sets. It means the elements may not appear in the same order as they are entered into the set. Moreover, a set does not accept duplicate elements.

There are two sub types in sets –

  1. set data type
  2. frozenset data type

set data type –

To create a set , we should enter the elements separated by commas inside curly braces {}.

In [27]: s = {50, 10, 6, 100, 5}

In [28]: for item in s:
    ...:     print(item)

In [29]: 

frozenset data type –

The frozenset data type is same as the set data type. The main difference is that the elements in the set data type can be modified whereas the elements of frozenset can not be modified.

We can create a frozenset by passing a set to frozenset() function.

In [29]: s = {50, 10, 6, 100, 5}

In [30]: fs = frozenset(s)

In [31]: fs
Out[31]: frozenset({5, 6, 10, 50, 100})

Mapping Types –

A map represents a group of elements in the form of key value pairs so that when they key is given, we can retrieve the value associated with it. The dict data type is an example for a map. The dict represents a dictionary that contains pairs of elements such that the first element represents they key and the next one becomes its value. The key and its value should be separated by a colon ( : ) and every pair should be separated by a comma. All the elements should be enclosed inside curly brackets {}.

Let’s create a dictionary which contains price of various stocks.

In [32]: stock_price = {'icici': 820, 'sbi': 600, 'reliance': 1400, 'itc': 300}

We can do various operation on dictionary. For example we can get the value associated with a key like this

In [33]: stock_price['icici']
Out[33]: 820

User-defined Data types –

The data types which are created by the programmers are called ‘user-defined’ data types. For example an array, a class or a module us user-defined data types. We will discuss about these data types in our upcoming posts.

Rating: 1 out of 5.

Leave a Reply