Data Analytics

The Essential Role of Data Types in Python Programming

Sumer Pasha

Sumer Pasha

Oct 01 - 3 min read

Introduction

Data Type are like the tools in a computer's toolbox, helping organize and work with information effectively. There are two main types: primitive, which are like the fundamental tools, and non-primitive, which are more complex and versatile. Just as a carpenter needs different tools for different tasks, computer scientists use various data type to handle different kinds of data in their programs. Understanding these types is key to creating efficient and powerful computer programs.

Python Data Type:

Data types are classifications that specify which type of value a variable can hold. The interpreter uses these data types to understand how to operate on the data and how to store it in memory.

Generally, Python Data Type can be divided into two categories in computer science:

Primitive Data Type:

These are the fundamental building blocks for data manipulation. They contain simple, immutable values.

Integers:-

Integers are whole numbers that do not have any fractional or decimal parts. Used to represent whole numbers from negative infinity to infinity. Example: -

A = 9

B = -78

Float: -

"Float" stands for 'floating point number'. Represent rational numbers with decimal figures Example: -

C = 2.11

D = -5.11

String: -

  • It’s a collection of alphabets and words or Character
  • Creating of string by enclosing with single or double Quotes.
  • Strings are immutable, meaning their values cannot be changed after they are created. Instead, operations on strings usually create new strings.
  • Strings have a length, which is the number of characters they contain.
  • Strings can be concatenated (joined together) using the + operator or specific string concatenation functions.
  • String can be accessed using indexing.
  • Strings support various manipulation operations.

Note: -

  • Mutable Example: -
E = ‘Sameer’

F = “Cookies”

G = ‘10’

# Python String Methods; -

# Concatenation

str1 = 'Hello'

str2 = ' World's

result = str1+str2

print(result) #Output: “Hello World”

# Length

print(len(result))

# Substring

print(result[6:12])

# Uppercase and Lowercase

print(result.upper())

print(result.lower())

# Replace

print(result.replace('

World', 'Universe'))

# Find

print(result.find('Hello'))

# Split

str3 = '!   '

result1 = result+str3

print(result1)

print(result1.strip())

# It removes the space after word

“Hello World”. Capitalize ()

 “Hello World”. count (‘0’)

“Hello World”. isdecimal ()

“Hello World”. isdigit ()

“Hello World”. islower ()

“Hello World”. isnumaric ()

Boolean

This built-in data type can take up the values: True and False, which often makes them interchangeable with the integers 1 and 0. Booleans are useful in conditional and comparison expressions

Example: -

Boolean Variable:

is_true = True

is_false = False

print(is_true)  # Output: True

print(is_false)  # Output: False

# Boolean Expression: -
x = 5

y = 10

# Comparison operators return Boolean values

is_equal = x == y

is_not_equal = x != y

print(is_equal)      # Output: False

print(is_not_equal)  # Output: True

# Logical Operator: 

a = True

b = False

# Logical AND

result_and = a and b

# Logical OR

result_or = a or b

# Logical NOT

result_not = not a

# Conditional Statements:

number = 42

if number > 50:

    print("The number is greater than 50.")

else:

    print("The number is not greater than 50.")

Data Type Conversion in Primitive Data Type: -

  • Data type conversion, also known as type casting
  • The process of converting a variable from one data type to another.
# Converting Integer to float

a = 5

b=float(a)

print('b is {} and type of b is {}'.format(b, type(b)))

# Converting float to Integer

a = 5.0

a=int(b)

print('a is {} and data type of a is {}'.format(a, type(a)))

# Converting Integer to String

a = 5

b = str(a)

print(b)

print(type(b))

# Converting float to String

a = 2.5

b = str(a)

print(b)

print(type(b))

# Converting String to Integer or float

# When converting a string to an integer or float, the string must be a valid numerical value; otherwise, it trough’s an error like 

“ValueError: invalid literal for int() with base 10”

c='10'

d,e = int(c), float(c)

print('d is {} and e is {}'.format(d,e))

# invalid conversion 

sa = 'sameer'

sam = int(sa),float(sa)

print(sam) #ValueError: invalid literal for int() with base 10: 'sameer'

Non-Primitive Data Type: -

List: -

  • A list is a versatile and mutable collection of elements in Python.

Note:

  • Mutable: Elements can be added, removed, or modified after the list is created.

  • It is ordered, meaning the elements have a specific sequence, and it allows for the storage of various data types within the same list (Heterogeneous).

  • Lists are defined by enclosing comma-separated values in square brackets ([ ]).

List Method: -

a is list, a = [ 1, 2, 3]

a.append()

a.extend()

a.insert()

a.remove()

a.pop()

a.count()

a.sort()

a.copy()

a.index()

a.reverse()

a.len()

Example:
# Creating a list

fruits = ["apple", "banana", "orange", "grape"]

# Accessing elements

print(fruits[0])  

# Modifying elements

fruits[1] = "kiwi"

print(fruits)  

# Adding elements

fruits.append("melon")

print(fruits)  

# Removing elements

# Removes the first occurrence of the specified element.

fruits.remove("orange")

print(fruits)  

# List length

# finding lenght of the list

print(len(fruits))  

# Append

#Adds an element to the end of the list.

fruits.append("pear")

# Insert

# Inserts an element at a specific index.

fruits.insert(1, "pineapple")

# Pop

# Removes and returns the element at the specified index. If no index is provided, it removes and returns the last element.

popped_fruit = fruits.pop(2)

# Index

# Returns the index of the first occurrence of the specified element.

index_of_apple = fruits.index("apple")

print(index_of_apple)

# Count

# Returns the number of occurrences of the specified element.

num_apples = fruits.count("apple")

print(num_apples)

# Sort

# Sorts the elements of the list in ascending order.

# sorting the list defult ascending order

fruits.sort()

fruits.sort(reverse=True)

# Reverse

# Reverses the order of the elements in the list.

fruits.reverse()

# Display the final list

print("Final List:", fruits)

Tuple: -

  • A tuple is an ordered and immutable collection of elements in Python.
  • It is ordered, meaning the elements have a specific sequence, and it allows for the storage of various data types within the same list (Heterogeneous).
  • but once a tuple is created, its elements cannot be modified (Immutable).
  • Tuples are defined by enclosing comma-separated values in parentheses.

Example:

# Creating a tuple

coordinates = (3, 7)

# Accessing elements

x = coordinates[0]  

y = coordinates[1]  

# Tuple unpacking

a, b = coordinates

print(a, b)  

# Length of a tuple

length = len(coordinates)  

# Immutability

# Uncommenting the line below will result in an error since tuples are immutable.

#coordinates[0] = 5

# Creating a new tuple with additional element

new_coordinates = coordinates + (5,)

# Displaying the final results

print("Original Coordinates:", coordinates)

print("New Coordinates:", new_coordinates)

Dictionary: -

A dictionary is an unordered collection of key-value pairs in Python. Each key in a dictionary must be unique, and it is associated with a specific value. Dictionaries are defined by enclosing key-value pairs in curly braces {}.

Characteristics:

  • Dictionary is mutable but unordered
  • All the elements are enclosed within flower brackets {}.
  • Each element is separated by comma
  • Each element is nothing but a 'KEY:VALUE' pair.
  • KEY must be a single element and unique
  • VALUE can be of any type like int, str, float, list, tuple.

Syntax Example:

Dictionary = {Key1:Value1, Key2:Value2, Key3:Value3}

Example:

# Creating a dictionary

student_info = {'name': 'John', 'age': 20, 'grade': 'A'}

# Copying the dict

new_dict = student_info.copy()

print(new_dict)

# Accessing elements

# Accessing values using keys.

name = student_info['name']  

age = student_info['age'] 

# get method

age = new_dict.get('age')

print(age)

#items method

items = new_dict.items()

print(items)

# keys method

keys = new_dict.keys()

print(keys)

#values method

values = new_dict.values()

print(values)

# Modifying elements

# Modifying the value associated with a key.

student_info['grade'] = 'B'

print(student_info)

new_dict.update({'age':24})

print(new_dict)

country = new_dict.setdefault('country','india')

print(country)

print(new_dict)

# Adding elements

# Adding new key-value pairs.

student_info['gender'] = 'Male'

print(student_info)  

# Removing elements

# Removing key-value pairs.

del student_info['age']

print(student_info)  

popi = new_dict.pop('grade')

print(popi)

# Dictionary length

# Determining the number of key-value pairs in a dictionary.

length = len(student_info)

Sets: It is defined by enclosing comma-separated values in curly braces {}.

Characteristics:

  • Unordered: Elements in a set do not have a specific sequence.
  • Unique Elements: A set cannot contain duplicate elements.
  • Each element/item must be unique
  • Mutable: Elements can be added or removed after the set is created.
  • Sets remove duplicate values and returns sorted values

Methods:

a = {1, 2, 3, 4, 5}

a.add(5)

a.remove(3)

len(a)

set operation (union, intersection, difference)

# Creating a set

unique_numbers = {1, 2, 3, 4, 5}

# Adding elements

# Adding elements to a set.

unique_numbers.add(6)

print(unique_numbers) 

# Removing elements

# Removing elements from a set.

unique_numbers.remove(3)

print(unique_numbers)  


# Set length

# Determining the number of elements in a set.

length = len(unique_numbers)  

print(length)

# Set operations

set1 = {1, 2, 3}

set2 = {3, 4, 5}

# Set operations like union, intersection, and difference.

union_set = set1.union(set2)  

intersection_set = set1.intersection(set2)  

difference_set = set1.difference(set2)  

# Displaying the final results

print("Original Set:", unique_numbers)

print("Union Set:", union_set)

print("Intersection Set:", intersection_set)
print("Difference Set:", difference_set)

Non Primitive Data Type Conversion: -

# List to Tuple (and Vice Versa):
my_list =[1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple) # From Tuple to List: my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list) # List of Tuples to Dictionary: my_list_of_tuples = [("apple", 5), ("banana", 2), ("orange", 3)]
my_dict = dict(my_list_of_tuples)
print(my_dict) # Tuple to Dictionary: my_tuple = (("apple", 5), ("banana", 2), ("orange", 3)) my_dict = dict(my_tuple) print(my_dict) # Dictionary to List of Tuples my_dict = {"apple": 5, "banana": 2, "orange": 3} my_list_of_tuples = list(my_dict.items()) print(my_list_of_tuples) # Set to List (and Vice Versa) # From Set to List: my_set = {1, 2, 3, 4, 5} my_list = list(my_set) print(my_list) # From List to Set: my_list = [1, 2, 2, 3, 4, 4, 5] my_set = set(my_list) print(my_set) # Set to Tuple (and Vice Versa) # From Set to Tuple: my_set = {1, 2, 3, 4, 5} my_list = tuple(my_set) print(my_list) # From tuple to Set my_list = (1, 2, 2, 3, 4, 4, 5) my_set = set(my_list) print(my_set)

Conclusion:

In summary, both primitive and non-primitive data structures are essential in the world of computer science and programming. Primitive structures act as the foundation, serving as the essential building blocks. On the other hand, non-primitive structures provide advanced methods for arranging and handling data, adding complexity and flexibility to the programmer's toolkit.

about the author

Sumer Pasha is a Digital Automation Engineer with Analogica India. He is a python developer and uses python to develop internal utilities for Analogica.