Python Programming - Understanding Data Type

Python Programming – Understanding Data Type

The type of data value that can be stored in an identifier such as a variable is known as its data type. If a variable, roll_no is assigned a data value of 121 that means the variable is capable of storing integer data. Similarly, if a variable height is assigned a data value of 5.11, then it would be able to hold real data. In python language, every value has a data type. Since everything is an object in Python programming data types are actually classes and variables are instances of the classes. Python language has standard data types that are used to define operations possible on them and the storage method for each of them: Python language supports seven standard built-in data types listed below:

  1. Number: represents numeric data to perform mathematical operations.
  2. String: represents text characters, special symbols, or alphanumeric data.
  3. List: represents sequential data that the programmer wishes to sort, merge, etc.
  4. Tuple: represents sequential data with a little difference from the list.
  5. Set: is used for performing set operations such as intersection, difference, etc with multiple values.
  6. Dictionary: represents a collection of data that associate a unique key with each value.
  7. File: represents data that can be stored permanently as a document on a computer.

Now, we will discuss each data type in brief. The complete detail of Python data types is given in Chapter 5.

Python Numbers

Python language supports four different numerical data types as described below:

  1. int: supports signed integer values.
  2. long: supports long integers that can be represented in Octal and Hexadecimal.
  3. float: supports floating-point real values.
  4. complex: supports complex numbers.

As presented above, integers, floating-point numbers, and complex numbers fall under the Python number category. They are defined as int, float, and complex classes in Python. The function type ( ) can be used to determine, which class a variable or a value belongs to, and the function instance ( ) is used to check if an object belongs to a particular class.

Also Read: Python Interview Questions on Python Thread Management

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. Complex numbers are written in the form x+yj, where x represents the real part and y represents the imaginary part. The creation of a number of objects is described in Code 2.7. (interactive mode):

Code: 2.7. Illustration of number data type

>>>i = 123456789 # variable i is assigned an integer value
>>> f = 9.8765432112345679564 # variable f is assigned a floating-point value
>>> f
>>> c = 5+9j # variable c is assigned a complex number
# value


The output of floating-point numbers goes up to 15 decimal places. So, in Code 2.7., 9564 is truncated from the value of variable f.

To determine the type of a variable type ( ) function is used as shown in the Code: 2.8.

Code: 2.8. Illustration of type () function

>>> type(i)
< class ‘int’>
>>> type(f)
< class ‘float-’>
>>>isinstance(5+9j, complex)

The reference to a variable can’ be deleted by using the statement given in Code 2.9.

Code: 2.9. Illustration of del keyword

del var_name
for instance,
del i
del i, f, c
del var1[, var2[,var3[…,varN]]]]
delif, ft, c[,…,

A few examples of numbers are described below:



Python allows the use of lowercase 1 with the long data type, but it is advised that the programmer should use an uppercase L to avoid ambiguity with the number 1. ion displays long integers with an uppercase L.

Python Strings

Strings are identified as a contiguous set of characters represented in the quotation marks. Python language allows for either pair of single or double-quotes. Subsets of strings can be taken using the slice operation ([] and [i]) with the index starting at 0 at the beginning of the string and -1 at the end or we can say that string is a sequence of Unicode characters. For instance, consider Code. 2.10., where each Python statement is explained by means of comment.

Code: 2.10. Illustration of Python strings

>>>str = “Hello Python”
<cla$s ‘str’>
>>> print(str) # It will print the complete string
Hello Python # It will print the value at 0 index
>>>str[2:5] # it will print 3rd to 5th character
>>>str[2:] # it will print 3rd to the last character
llo Python
>>>str*2 #it will print the valueof str twice
Hello Python Hello Python
>>>str+”Test” # it will concatenate Test with Hello Python
Hello Python Test

Python Lists

Lists are the most versatile and flexible compound data types of the Python language. The list is an ordered sequence of items. All the items in a list do not need to be of the same type. That is a list can hold heterogeneous data types. To a certain extent, lists are similar to arrays in C, C++, or Java. The major difference between array and list in Python is that all the items that belong to a list can be of heterogeneous or different data types. Declaring a list is quite simple. A list contains items separated by commas and enclosed within square brackets []. Consider the Code 2.11.

Code: 2.11. Declaration of List in Python

>>>a=[1, 3.2, ‘programming’]
<class Tist’>

A slicing operator [ ] can be used to extract an item or a range of items from a list. Similar to C, the list index starts from 0 in Python. Consider the Code 2.12. to see the use of the slicing operator.

Code: 2.12. Illustration of slicing operator

>>>a=[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
>>> a[5] # prints 6th value in the list
>>5>a[0:4] # prints 1st to 5th value in the list
[5, 10, 15, 20,25]
>>>a[5:] # prints 6th to last value in the list
[30, 35, 40,45, 50]

The plus sign (+) is used for concatenation and the asterisk (*) is the repetition operator. For instance, consider Code 2.13.

Code: 2.13. Illustration of concatenation (+) and repetition (*) operators

>>> print a*2                       # prints the list two
# times
[5, 10, 15, 20, 25, 30, 35, 40,45, 50, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
>>>b=[6, 12, 18]
>>>print (a+b) #prints the
# concatenated lists
[5, 10, 15,20, 25, 30, 35,40,45, 50, 6,12,18]

Lists are mutable, which means the values of elements of a list can be altered. For instance, see Code: 2.14.

Code: 2.14. Illustration of editing list in Python

>>>a=[l, 2, 3]                    # a is list with values 1, 2, 3
>>>a[2]=4                         # a[2] is given a new value 4
>>>a                                  # prints the altered list

Python Tuples

A tuple is an ordered sequence of items same as a list. A tuple consists of a number of values separated by commas. Unlike lists, tuples are enclosed within parenthesis (). The only difference between lists and tuples is that tuples are immutable, i.e., tuples once created cannot be modified. They are used to write protect the data and they are usually faster than the lists as they cannot be changed dynamically. Tuples are defined as shown in Code 2.15.

Code: 2.15. Illustration of declaring a Tuple

>>> t = (7, ‘Python’, 2+8j)
>>> type(t)
<class ‘tuple’>

Similar to the list the slicing operator [ ] is used to extract items from the tuple. However, we cannot edit data into the tuple, see Code: 2.16.

Code: 2.16. Illustration of using slicing operator with Tuple

>>> t[0]=8                          #  altering a tuple value
#Generates an error message


Tuples can be thought of as read-only lists

Python Sets

Set is an unordered collection of unique items. Set is defined by values separated by commas inside braces {}. Items in a set are not ordered. A set is defined as shown in Code 2.17.

Code: 2.17. Illustration of declaring a set in Python

>>> a = { 15,20, 13,45,67}
>>> a
{13, 15,20,45, 67}
>>> type(a)
<class ‘set’>.

The operations such as union, intersection can be performed on the sets. Sets have unique values and they eliminate duplicates. See Code 2.18. for instance,

Code: 2.18. Set Illustration

>>>.a= {1,2, 2,2, 3,3}
>>> a

Since sets are unordered collections, indexing has no meaning in sets. Therefore, the slicing operator [ ] does not work on sets and generates errors as displayed below in Code 2.19. and in Fig. 2.2 (interactive mode).

Code: 2.19. Illustration of using slicing operator with set

>>> a = {1,2, 2,2, 3,3}
>>> a
>>> a[1]
Generates error message

Python Programming - Understanding Data Type chapter 2 img 1

Python Dictionaries

Dictionary is an unordered collection of key-value pairs. It is generally used to operate on a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. Python language’s dictionaries are kind of hash table type. They work like associate arrays or hashes found in PERL consist of key-value pairs.

Dictionary key can be of almost any Python type but usually numbers or strings. Values, on the other hand, can be any arbitrary Python object dictionaries enclosed by curly braces { }. The values are assigned and accessed by using square brackets []. For instance, see Code 2.20.,

Code: 2.20. Illustration of Python dictionary

>>>dict = { }
>>>diet [‘one’] = “ this is one value”
>>>dict[2] = “this is numeric two”

Another way of using dictionary is shown in Code 2.21.

Code: 2.21.

>>> dict2 = { ‘name’: ‘Smith’, ‘code’: 1234, ‘dept’:’HR’}
>>>print (dict[‘one’])
This is one value
>>>print (dict[2])
This is numeric two
>>>print dict2
‘name’: ‘Smith’, ‘code’: 1234, ‘dept’:’HR’
>>> dict2[‘name’]
>>> dict2[‘code’]

Python Files

The file data type is used in Python to store and work with files on the computer or on the Internet. For working on a file either an existing one or a new file, it must be opened using the open ( ) function as open(“newFile”). A lot can be done on files in Python which we will leam in Chapter 9 File Management in Python.

Python Tutorial

Leave a Reply

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