Python Programming

Data Types in Python

Data Types in Python

Introduction

Data type represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming language, data types are classes and variables are the instances(objects) of these classes. Python is a dynamically typed language; hence it is not needed to define the variable type while declaring it. The interpreter implicitly binds the value with its type.

EXAMPLE:

a=10

The variable ‘a’ holds an integer value of ten and we did not define its type. Python interpreter will automatically interpret variable ‘a’ an integer type. Python provides us with the type() function to check the type of variable used in the program.

Standard Data types:

A variable can hold different types of values. For example, a person’s name must be stored as a string whereas its id must be stored as an integer.

The data types defined in Python are given below.

  1. Numeric
  2. Sequence type
  3. Boolean
  4. Set
  5. Dictionary

Numeric:

This data type represents the data that has a numeric value. A numeric value can be an integer, floating number, or even complex number which are defined as int, float, and complex class respectively.

  • Integers: This value is represented by int class. It contains positive or negative whole numbers. In python, there is no limit to how long an integer value can be. Ex: 4, 60, 7456, -98, etc.
  • Float: This value is represented by the float class. It is specified by a decimal point. Ex: 2.2, 0.4763, etc.
  • Complex Numbers: This value is represented by a complex class. It is specified as (real part) + (imaginary part)j. Ex: 4+9j, 3-7j, etc.

Example Code:

n=6
print(type(n))

n=0.25
print(type(n))

n=4+9j
print(type(n))

Output:

<class 'int'>
<class 'float'>
<class 'complex'>

Sequence Type:

A sequence is the ordered collection of similar or different data types. The types of sequences are

  • String
  • List
  • Tuple

String:

It is represented by an str class. 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. A character is a string of length one.

Accessing elements of String:

Individual characters of a string can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the string.

Example Code:

String="Data Types in Python"
print("Initial String: ")
print(String)

print("\nFirst character of the String is: ")
print(String[0]);

print("\nLast character of the String is: ")
print(String[-1])

Output:

Initial String:
Data Types in Python

First character of the String is:
D

Last character of the String is:
n

List:

Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type. Lists can be created by just placing the sequence inside the square brackets[ ].

Accessing elements of the List:

Use the index operator [ ] to access an item in a list. Negative sequence indexes represent positions from the end of the array.

Example code:

#accessing elements of a list
list1 = ['Carrot','Beetroot','Apple','Banana'];
list2=[1,2,3,4,5];
print("list1[0:2]: ",list1[0:2])
print("list2[2:4]: ",list2[2:4])

Output:

List1[0:2]:  ['Carrot', 'Beetroot']
List2[2:4]:  [3, 4]

Tuple:

It is represented by a tuple class. Just like a list, the tuple is also an ordered collection of Python objects. The only difference between a tuple and a list is that tuples are immutable i.e. cannot be modified after it is created. Tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use of parentheses. Tuples can contain any number of elements and any datatype.

Accessing elements of a tuple:

To access the tuple items refer to the index number. Nested tuples are accessed using nested indexing.

Example code:

tuple1 = ('Python', 'C++' , 'Java' , 'C');
tuple2 = (2,4,6,8,10);
print("tuple1[0]: ",tuple1[0]);
print("tuple2[2:5]: ", tuple2[2:5]);

Output:

tuple1[0]:  Python
tuple2[2:5]:  (6, 8, 10)

Boolean:

It is denoted by the class bool. It is a data type with one of the two built-in values, True or False. True and False with a capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

Example Code:

A = True
print(type(A))

B = False
print(type(B))

C = (9==6)
print(C)

Output:

<class 'bool'>
<class 'bool'>

False

Set:

Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’.

Accessing elements of Sets:

Since sets are unordered the items have no index. But it can be looped through the set items using a for loop or ask if a specified value is present in a set, by using the in keyword.

Example code:

Rainbowcolours = {"Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"}
print(Rainbowcolours)
print(type(Rainbowcolours))
#looping through the set elements
for i in Rainbowcolours:
    print(i)

Output:

{'Violet', 'Yellow', 'Green', 'Blue', 'Indigo', 'Red', 'Orange'}
<class 'set'>
Violet
Yellow
Green
Blue
Indigo
Red
Orange

Dictionary:

Dictionary is an unordered collection of data values, used to store data values like a map. Dictionary holds key-value pairs to make it more optimized. Each key-value pair in a Dictionary is separated by a colon, whereas each key is separated by a ‘comma’. A dictionary can be created by placing a sequence of elements within curly { } braces, separated by ‘comma’. It can also be created by the built-in function dict(). An empty dictionary can be created by just placing it in curly braces{ }.

Accessing elements of Dictionary:

To access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is also a method called get() to access an element from a dictionary.

Example Code:

#accessing the elements of a dictionary
dict = {'Name':'Sam','Age':'12','Sex':'Male'}
print("dict['Name']: ",dict['Name'])
print("dict['Sex']: ",dict['Sex'])

Output:

dict['Name']:  Sam
dict['Sex']:  Male

Conclusion:

Understanding Python data types allows you to take full advantage of the languages’ design as efficiently and effectively as possible.