Tuesday, 10 June 2025

Python Datatypes

 Introduction to Python Datatypes

In Python, everything is an object. This means that every value you work with (numbers, strings, collections, functions, etc.) is an instance of a class with its associated methods and attributes. Python’s dynamic typing means you don’t declare a variable’s type explicitly—the interpreter infers the type at runtime.


Basic (Primitive) Data Types

a. Numeric Types

Python supports several numeric types:


Integers (int): Whole numbers, e.g., 10, -5.


Floating-Point Numbers (float): Numbers with a decimal point, e.g., 3.14, -0.001.


Complex Numbers (complex): Numbers with a real and an imaginary part, e.g., 2 + 3j.


Examples:

# Integer

a = 10

print("a =", a, "type:", type(a))  # Output: a = 10 type: <class 'int'>


# Float

b = 3.14

print("b =", b, "type:", type(b))  # Output: b = 3.14 type: <class 'float'>


# Complex Number

c = 2 + 3j

print("c =", c, "type:", type(c))  # Output: c = (2+3j) type: <class 'complex'>


Explanation: These types allow you to work with whole numbers, fractions, and numbers that include complex calculations. They form the very basics for arithmetic operations in Python.


b. Strings (str)

Strings are sequences of characters used to store text. In Python, strings are immutable, meaning once you create a string, you cannot change its content (but you can create new strings based on it).


Examples:

# A simple string

s = "Hello, Python!"

print(s)  # Output: Hello, Python!


# String indexing and slicing

print(s[0])     # Output: H

print(s[-1])    # Output: !

print(s[7:13])  # Output: Python


# String methods

print(s.upper())  # Output: HELLO, PYTHON!

print(s.lower())  # Output: hello, python!



C .Booleans (bool)

Booleans represent truth values—either True or False. They are essential for control flow and conditional expressions.


Example:

flag = True

print("flag:", flag, "type:", type(flag))  # Output: flag: True type: <class 'bool'>


# Using booleans in conditions

if flag:

    print("The flag is set to True!")



Explanation: Booleans are fundamental to decision-making in your code. They commonly result from comparisons (e.g., ==, <, >) and logical operations (and, or, not).


Collection Data Types

Python offers several built-in collection types to group multiple data items


Lists (list)

Lists are ordered and mutable (changeable) collections that allow duplicate elements.


Examples:

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

print("numbers:", numbers, "type:", type(numbers))


# List operations

numbers.append(6)

print("After append:", numbers)


# Slicing a list

print("First three elements:", numbers[:3])


Tuples (tuple)

Tuples are similar to lists, but are immutable—once created, they cannot be modified. 

They are ideal for fixed sequences of data

Examples:

dimensions = (1920, 1080)

print("dimensions:", dimensions, "type:", type(dimensions))


# Accessing tuple items

print("Width:", dimensions[0])


Dictionaries (dict)

Dictionaries are unordered collections of key-value pairs. They offer fast lookup and are mutable.


Example:

person = {

    "name": "Alice",

    "age": 30,

    "city": "New York"

}

print("Dictionary:", person, "type:", type(person))


# Accessing values by key

print("Name:", person["name"])


# Modifying dictionary

person["age"] = 31

print("Updated:", person)


Sets (set)

Sets are unordered collections of unique elements. They are mutable, but their elements must be immutable (e.g., numbers, strings, tuples).


Example:

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

print("Set:", unique_numbers, "type:", type(unique_numbers))  # Output: {1, 2, 3, 4, 5}


# Set operations

even_numbers = {2, 4, 6, 8}

print("Union:", unique_numbers | even_numbers)

print("Intersection:", unique_numbers & even_numbers)


Specialized and Advanced Data Types

a. None Type

The special constant None represents the absence of a value or a null value. It is its own datatype—NoneType.


Example:

result = None

print("result:", result, "type:", type(result))


Explanation: None is commonly used to signify that a variable has no value, similar to null in other programming languages


Bytes and Bytearray

Bytes: Immutable sequences of bytes, used for binary data.


Bytearray: A mutable sequence of bytes.


Example:

# Immutable bytes object

b = b"Hello"

print("Bytes:", b, "type:", type(b))


# Mutable bytearray object

ba = bytearray(b)

ba[0] = 74  # Changing the first byte to the ASCII of 'J'

print("Bytearray:", ba)


Memoryview

The memoryview object lets you access the internal data of an object that supports the buffer protocol (like bytes and bytearray) without copying.

Examples:

data = bytearray(b"Hello, world!")

mv = memoryview(data)

print("Memoryview:", mv[0:5].tobytes())  # Output: b'Hello'



Advanced: Custom Classes

Since everything is an object in Python, you can create custom datatypes using classes. This allows you to define both data and behavior.


Example:

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age


    def greet(self):

        return f"Hello, my name is {self.name}."


# Instantiating a custom datatype

alice = Person("Alice", 30)

print(alice.greet())

print("Type of alice:", type(alice))



Explanation: This is how you build more complex data structures by combining multiple attributes and methods into a single, reusable datatype.


Mutability vs. Immutability: A Key Concept

Understanding which datatypes are mutable (modifiable) and which are immutable (unchangeable) is crucial:


Datatype Mutable? Example Operation

int, float Immutable Reassignment creates a new object

str Immutable Methods like .replace() return a new string

tuple Immutable Cannot change individual elements

list Mutable append(), pop() modify the list

dict Mutable Adding or updating key-value pairs

set Mutable Methods like .add(), .remove()








Python variables or variables

 What Is a Variable?


A variable is simply a name that points to an object in memory. Unlike many other languages, Python variables do not require explicit type declarations. When you assign a value to a variable, Python automatically infers its type.


# An integer variable

x = 10


# A floating-point variable

pi = 3.14


# A string variable

name = "Alice"

Here, x, pi, and name are variables that reference an integer, a float, and a string respectively.



2 .

Basic Assignment and Dynamic Typing

Python variables are dynamically typed, meaning you can reassign them to objects of different types over time. This flexibility helps you write concise code.


Example:

value = 100    # 'value' is an integer

print(value)   # Output: 100


value = "Python is fun!"

print(value)   # Now 'value' points to a string: Output: Python is fun!


Notice how the type of value changes automatically based on what you assign to it.



3. Variable Naming Conventions

When naming variables, keep these guidelines in mind:


A variable name must start with a letter (a–z, A–Z) or an underscore (_).


Subsequent characters can be letters, digits (0–9), or underscores.


Avoid using Python's reserved words (like if, for, class, etc.).


Example:

_valid = 1

valid_name = "Yes"

# 2nd_var = 10  # This would be invalid, because variable names cannot start with a number.


4 .

Multiple Assignment and Swapping

Python lets you assign values to multiple variables at once. You can also swap values in a single line without needing a temporary variable.


Multiple Assignment Example:


a, b = 5, 10

print(a, b)  # Output: 5 10


# Using the same value for multiple variables

x = y = z = 0

print(x, y, z)  # Output: 0 0 0


Swapping exmples 

# Traditional swapping without a temporary variable using tuple-unpacking

a, b = 1, 2

a, b = b, a

print("a =", a, "b =", b)  # Output: a = 2  b = 1


5. Mutable vs. Immutable Variables

Variables point to objects. Some objects in Python are mutable (their state can be changed), while others are immutable.


Immutable objects: e.g., integers, floats, strings, and tuples.


Mutable objects: e.g., lists, dictionaries, and sets.


Immutable Example:

a = 10

b = a  # Both 'a' and 'b' reference the integer 10

a = 20  # 'a' now references a new integer 20

print(b)  # 'b' still references 10 because integers are immutable.



Mutable examples:

list1 = [1, 2, 3]

list2 = list1  # Both variables reference the same list

list1.append(4)

print(list2)  # Output: [1, 2, 3, 4] - changes to 'list1' reflect in 'list2'


6.  Local vs. Global Variables

The scope of a variable refers to the region of your code where that variable is accessible.


Global variables: Defined outside of functions and are accessible anywhere in the module.


Local variables: Defined within a function and accessible only within that function.


Example:


global_var = "I am global"  # Global variable


def display_variables():

    local_var = "I am local"  # Local variable

    print(local_var)         # Accessible inside the function

    print(global_var)        # Global variable accessible inside the function


display_variables()

# print(local_var)         # This would raise an error because 'local_var' is not in the global scope.



Using nonlocal in Nested Functions

When dealing with nested functions, use the nonlocal keyword to modify a variable from an enclosing (but non-global) scope.

def outer():

    message = "Hello"

    def inner():

        nonlocal message

        message = "Hello, modified!"

        print("Inner:", message)

    inner()

    print("Outer:", message)


outer()



This example shows how nonlocal works when you need to alter a variable defined in the outer function


Introspection with globals() and locals()

Python provides built-ins for introspecting the current namespace.


globals(): Returns a dictionary representing the global symbol table.


locals(): Returns a dictionary representing the current local symbol table.


Example:

x = 5


def my_function():

    y = 10

    print("Local namespace:", locals())


my_function()

print("Global namespace keys:", list(globals().keys()))



Deleting Variables ::

You can delete a variable using the del statement, which can be useful if you want to free up resources or remove an identifier from the namespace.


Example:

temp = "temporary value"

print(temp)  # Output: temporary value

del temp

# print(temp)   # This would raise a NameError since 'temp' is deleted.



Late Binding in Closures

A common pitfall in Python is the late binding behavior in closures, which can lead to unexpected results when creating functions in a loop.


Problematic Example:

funcs = [lambda: i for i in range(5)]

results = [f() for f in funcs]

print(results)  # All functions will reference the final value of 'i', often resulting in [4, 4, 4, 4, 4]



Corrected Example:


python

funcs = [lambda i=i: i for i in range(5)]

results = [f() for f in funcs]

print(results)  # Output: [0, 1, 2,3,4]




Using the id() Function for Memory Inspection

Since variables in Python are labels attached to objects, you can examine the identity (i.e., memory address) of the objects they reference using id().

Examples:


a = 1000

b = a

print("ID of a:", id(a))

print("ID of b:", id(b))


a = 2000  # Now 'a' points to a new object

print("After reassigning a:")

print("ID of a:", id(a))

print("ID of b (unchanged):", id(b))


Explanation:

This shows that when you reassign a variable, you are simply pointing the variable to a new object; the previous object may still exist if referenced by other variables





Datatypes: https://grasptechnology.blogspot.com/2025/06/python-datatypes.html