The Essential Role of Data Types in Python Programming
Introduction
Data Types 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 types 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:
Integers: -
Example: -
A = 9
B = -78
Float: -
Example: -
C = 2.11
D = -5.11
String: -
Note: -
Mutable
Example: -
E = ‘Sameer’
F = “Cookies”
G = ‘10’
Python String Methods; -
str1 = 'Hello'
str2 = ' World's
result = str1+str2
print(result) #Output: “Hello World”
2. Length
print(len(result))
3. Substring
print(result[6:12])
4. Uppercase and Lowercase
print(result.upper())
print(result.lower())
5. Replace
print(result.replace('World', 'Universe'))
6. Find
print(result.find('Hello'))
7. Split
str3 = '! '
result1 = result+str3
print(result1)
print(result1.strip())
It removes the space after word
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)
print(is_false)
Boolean Expression: -
x = 5
y = 10
# Comparison operators return Boolean values
is_equal = x == y
is_not_equal = x != y
print(is_equal)
print(is_not_equal)
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.
a = 5
b=float(a)
print('b is {} and type of b is {}'.format(b, type(b)))
Recommended by LinkedIn
a = 5.0
a=int(b)
print('a is {} and data type of a is {}'.format(a, type(a)))
a = 5
b = str(a)
print(b)
print(type(b))
a = 2.5
b = str(a)
print(b)
print(type(b))
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:
Note:
Mutable: Elements can be added, removed, or modified after the list is created.
List Method: -
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:
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:
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:
Methods:
a = {1, 2, 3, 4, 5}
Example:
# 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: -
1. List to Tuple (and Vice Versa):
my_list =[1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list)
2. 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)
3. Tuple to Dictionary:
my_tuple = (("apple", 5), ("banana", 2), ("orange", 3))
my_dict = dict(my_tuple)
print(my_dict)
4. 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)
5. Set to List (and Vice Versa)
1) From Set to List:
my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
print(my_list)
2) From List to Set:
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)
6. Set to Tuple (and Vice Versa)
1) From Set to Tuple:
my_set = {1, 2, 3, 4, 5}
my_list = tuple(my_set)
print(my_list)
2) 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.