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()
No comments:
Post a Comment