fbpx

Practical Applications of Python Data Types in Real-world Projects

Python Datatypes

INTRODUCTION

In programming, the data type of a variable defines what kind of value it can hold and what operations can be performed on it. Python, being a dynamically-typed language, automatically assigns a data type to variables at runtime based on their value. However, understanding Python’s data types is crucial for writing efficient, error-free code and making the most of Python’s capabilities.

Python offers a rich set of data types that cater to various needs, from handling simple text to managing complex structures. These data types include:

  • Text Type: str for storing strings.
  • Numeric Types: int, float, and complex for numeric computations.
  • Sequence Types: list, tuple, and range for managing ordered collections of data.
  • Mapping Type: dict for key-value pair storage.
  • Set Types: set and frozenset for collections of unique elements.
  • Boolean Type: bool for logical values (True or False).
  • Binary Types: bytes, bytearray, and memoryview for handling binary data.
  • None Type: NoneType for representing the absence of a value.

Datatypes:

It represents type of data passing to the computer.(it was a numeric , sequence, mapping, set, Boolean, binary)

Data types specify the size, range, and operations that can be performed on the variable.

Datatypes in python:

Text Type:

Str

Numeric Types:

int, float, complex

Sequence Types:

list, tuple, range

Mapping Type:

Dict

Set Types:

set, frozenset

Boolean Type:

Bool

Binary Types:

bytes, bytearray, memoryview

None Type:

NoneType

 

Text type: its  a type of data  that is used to store the characters and group of characters

Str=’a’(this is for storing the characters)

Str=”thenmozhi”(this is storing the group of characters”);  address = “””1234 Elm Street

Springfield

IL 62701″””

 

Numeric Types:

intfloatcomplex

 I=5;

f=12.22

num1 = 2 + 3j       # A complex number with real part 2 and imaginary part 3

print(type(num1))   # Output: <class ‘complex’>

Sequence types:

A list is a mutable (modifiable) sequence type that can store a collection of items, including mixed data types.

Disadavantages  present in the array:

  • Fixed Size
  • The size of an array is fixed at the time of its creation, making it inflexible for dynamic data storage. If the allocated size is too small, resizing the array is complex, and if it’s too large, memory is wasted.
  • Inefficient Insertions and Deletions:

Insertion and deletion is very difficult in case of array because we have to shift all the elements to right.

  • No Built-in Flexibility for Resizing
  • Unlike dynamic structures (e.g., lists in Python), arrays do not automatically resize. Developers must manually implement resizing or use alternative data structures.
  • Contiguous Memory Requirement
  • Arrays require contiguous memory blocks. For large arrays, finding such blocks can be challenging, especially in fragmented memory systems.
  • Homogeneity
  • Many programming languages enforce that all elements in an array must be of the same data type, limiting flexibility.
  • Limited Functionality
  • Arrays provide basic storage without built-in features like sorting, searching, or dynamic memory management. Developers must write custom code or use additional libraries.

python

List:

  • Ordered: The elements in a list maintain the order in which they are added.
  • Mutable:modify, add, or remove elements from a list.
  • Heterogeneous: A list can contain elements of different data types (e.g., integers, strings, other lists, etc.).
  • Indexed: You can access elements using zero-based indexing.

# Empty list

empty_list = []

 

# List with integers

int_list = [1, 2, 3, 4]

 

# List with mixed data types

mixed_list = [1, “hello”, 3.14, True]

 

# Nested list

nested_list = [[3,4], [5,2], [6,3]]                     

 

1. Accessing Elements:

 

Mylist=[1,2,3,4,5]

Print(Mylist[0])

Printf(Mylist[1])

2.Updating the elements:

Mylist[0]=12;

3.Adding the elements

Mylist.append(50) # Add to the end

Mylist.insert(1, 15) # Insert at index 1

4.Removing the elements:

my_list.pop()            # Removes the last element

my_list.remove(25)     

del my_list[1]         

print(my_list)           # Output: [10, 30, 40]

 

slicing the element:

sub_list = my_list[1:3] 

print(sub_list)          # Output: [30, 40]

Useful list methods:

my_list = [3, 1, 4, 1, 5]

# Length of the list

print(len(my_list))       # Output: 5

Tuple:

  • A tuple is an immutable sequence type in Python, meaning its elements cannot change once the tuple is created.
  • Tuples are defined by values separated by commas, optionally enclosed in parentheses ().

Syntax:

my_tuple = (1, 2, 3)empty_tuple = ()single_element_tuple = (42,)  # A comma is required for single-element tuples

Properties:

  • Immutable: Elements cannot be changed, added, or removed.
  • Ordered: Maintains the insertion order.
  • Supports multiple data types: Can store heterogeneous elements.

Example:

coordinates = (10.5, 20.3)print(coordinates[0])  # Access first element

Range:

  • range() is a built-in function in Python used to generate a sequence of numbers.
  • It is commonly used in loops, especially for loops.
  • The sequence produced by range() is immutable.

 

Syntax:

range(stop)              # From 0 to stop-1range(start, stop)       # From start to stop-1range(start, stop, step)  

1. dict (Dictionary)

  • A dictionary is a collection of key-value pairs. It is unordered and mutable.
  • Keys must be unique and immutable (e.g., strings, numbers, or tuples), and values can be any Python object.

Example:

my_dict = {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}print(my_dict[‘name’])  # Output: Alice

2. set

  • A set is an unordered collection of unique elements.
  • Sets do not allow duplicate values and are mutable.
  • Commonly used to eliminate duplicates from a list or perform mathematical set operations like union, intersection, and difference.

Example:

my_set = {1, 2, 3, 4}my_set.add(5)  # Adds an elementprint(my_set)  # Output: {1, 2, 3, 4, 5}

3. frozenset

  • A frozenset is similar to a set but is immutable (cannot be modified once created).
  • It can be used as a dictionary key because it is hashable.

Example:

my_frozenset = frozenset([1, 2, 3])# my_frozenset.add(4)  # This will raise an error because frozensets are immutableprint(my_frozenset)  # Output: frozenset({1, 2, 3})

4. bool (Boolean)

  • The bool type has two values: True and False.
  • Used for logical operations and condition checks.