Comprehensive Guide to Python's Nine Fundamental Data Types

  1. Integer (int)

The int type represents whole numbers in Python, including positive, negative, and zero values. Unlike many other programming lagnuages, Python integers have arbitrary precision, meaning they can grow as large as memory allows.

# Integer declarations
count = 42
temperature = -15
large_num = 9999999999999999999999

# Arithmetic operations
addition = count + temperature
subtraction = count - temperature
multiplication = count * 2
floor_division = count // 4
modulo = count % 5

print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Floor Division: {floor_division}")
print(f"Modulo: {modulo}")

  1. Float (float)

The float type handles real numbers with decimal points. Floats support scientific notation and are essential for calculations requiring fractional precision.

# Float declarations
price = 19.99
ratio = -0.618

# Scientific notation examples
scientific_large = 5.67e20  # 567000000000000000000.0
scientific_small = 3.21e-8  # 0.0000000321

# Float arithmetic
total = price + ratio
difference = price - ratio
product = price * ratio
quotient = price / ratio  # True division returns float

print(f"Total: {total}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")

  1. Boolean (bool)

The bool type represents logical values with only two possible states: True and False. Booleans are fundamental for control flow and conditional logic.

# Boolean assignment
is_active = True
is_deleted = False

# Comparison operations resulting in booleans
score = 85
passing = 60
print(score > passing)  # True
print(score == passing)  # False

# Logical operations
print(is_active and is_deleted)  # False
print(is_active or is_deleted)   # True
print(not is_active)             # False

# Boolean to integer conversion
print(int(is_active))   # 1
print(int(is_deleted))  # 0

  1. String (str)

Strings are immutable sequences of Unicode characters. They can be enclosed in single quotes, double quotes, or triple quotes for multi-line content.

# String creation
greeting = 'Hello'
message = "World"
multiline = """This is a
multi-line string"""

# String indexing and slicing
text = "Python Programming"
print(text[0])       # P
print(text[7:18])    # Programming
print(text[:6])      # Python
print(text[-11:])    # Programming

Common String Operations

Concatenation

first = "Hello"
second = "World"
combined = first + ", " + second
print(combined)  # Hello, World

Formatting

user = "Bob"
years = 25

# f-string (Python 3.6+)
print(f"{user} is {years} years old")

# format() method
print("{} is {} years old".format(user, years))

# % operator
print("%s is %d years old" % (user, years))

Search and Replace

sentence = "The quick brown fox"
print(sentence.find("quick"))           # 4
print(sentence.replace("fox", "dog"))   # The quick brown dog

Split and Join

data = "red,green,blue"
parts = data.split(",")
print(parts)                    # ['red', 'green', 'blue']
print("-".join(parts))          # red-green-blue

Case Conversion

mixed = "Hello World"
print(mixed.upper())    # HELLO WORLD
print(mixed.lower())    # hello world

Stripping Whitespace

padded = "  centered  "
print(padded.strip())    # centered
print(padded.lstrip())   # "centered  "
print(padded.rstrip())   # "  centered"

  1. None Type

None is a special constant representing the absence of a value or a null value. It's frequently used for default arguments and indicating missing data.

# Variable initialization
result = None
print(result)  # None

# Function return value
def process_data():
    # No explicit return defaults to None
    pass

value = process_data()
print(value)  # None

# Conditional checking
config = None
if config is None:
    print("Configuration not set")

  1. List

Lists are mutable, ordered sequences that can hold heterogeneous elements. They support dynamic resizing and various manipulation methods.

Creating Lists

# List initialization
digits = [1, 2, 3, 4, 5]
mixed = [10, "text", 3.14, [1, 2]]
empty = []

Accessing Elements

nums = [10, 20, 30, 40, 50]

print(nums[0])    # 10 (first element)
print(nums[-1])   # 50 (last element)
print(nums[2:4])  # [30, 40] (slicing)

Modifying Lists

items = [1, 2, 3, 4]

# Update by index
items[0] = 100

# Append element
items.append(5)

# Insert at position
items.insert(1, 150)

# Remove by value
items.remove(150)

# Remove by index and return
last = items.pop()

# Delete by index
del items[0]

print(items)  # [2, 3, 4]

Iterating Lists

colors = ["red", "green", "blue"]

for color in colors:
    print(color)

  1. Tuple

Tuples are immutable, ordered sequences. Once created, their contents cannot be modified, making them ideal for fixed data collections.

Creating Tuples

# Tuple creation
coordinates = (10, 20, 30)
single_item = (1,)  # Comma required for single element
empty_tuple = ()
from_list = tuple([1, 2, 3])

# Tuple with mixed types
record = (1, "Alice", 95.5, [10, 20])

Accessing Elements

point = (5, 10, 15)

print(point[0])   # 5
print(point[-1])  # 15

Immutability

data = (1, 2, [3, 4])

# Cannot modify tuple directly
# data[0] = 100  # TypeError

# Can modify mutable elements inside tuple
data[2].append(5)
print(data)  # (1, 2, [3, 4, 5])

Tuple Methods

values = (1, 2, 2, 3, 2)

print(values.count(2))   # 3
print(values.index(3))    # 3

  1. Dictionary

Dictionaries are mutable collections of key-value pairs. Keys must be unique and immutable, while values can be of any type.

Creating Dictionaries

# Dictionary creation
profile = {"name": "Alice", "age": 28, "city": "Boston"}
numeric_keys = {1: "one", 2: "two"}
empty_dict = {}

Accessing Values

user = {"name": "John", "age": 30}

print(user["name"])              # John
print(user.get("job", "N/A"))    # N/A (safe access)

Modifying Dictionaries

person = {"name": "Jane", "age": 25}

# Update existing key
person["age"] = 26

# Add new key-value pair
person["city"] = "Chicago"

# Remove key-value pair
del person["age"]

# Pop and return value
name = person.pop("name")

print(person)  # {'city': 'Chicago'}

Iterating Dictionaries

scores = {"math": 95, "science": 88, "history": 92}

# Iterate keys
for subject in scores:
    print(subject)

# Iterate values
for score in scores.values():
    print(score)

# Iterate key-value pairs
for subject, score in scores.items():
    print(f"{subject}: {score}")

Dictionary Methods

data = {"a": 1, "b": 2}

print(data.keys())    # dict_keys(['a', 'b'])
print(data.values())  # dict_values([1, 2])
print(data.items())   # dict_items([('a', 1), ('b', 2)])

# Update with another dictionary
data.update({"c": 3, "d": 4})

# Clear all entries
data.clear()

  1. Set

Sets are unordered collections of unique elements. They support mathematical set operations and automatically eliminate duplicates.

Creating Sets

# Set creation
unique_nums = {1, 2, 3, 4}
from_list = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}
empty_set = set()  # NOT {} which creates empty dict

Accessing Elements

letters = {"a", "b", "c"}

# Cannot access by index (unordered)
# Must iterate
for letter in letters:
    print(letter)

Modifying Sets

nums = {1, 2, 3}

# Add element
nums.add(4)

# Remove element (raises error if not found)
nums.remove(2)

# Discard element (no error if not found)
nums.discard(5)

# Update with another set
nums.update({5, 6})

print(nums)  # {1, 3, 4, 5, 6}

Set Operations

set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# Union
print(set_a | set_b)              # {1, 2, 3, 4, 5, 6}
print(set_a.union(set_b))          # Same result

# Intersection
print(set_a & set_b)               # {3, 4}
print(set_a.intersection(set_b))    # Same result

# Difference
print(set_a - set_b)               # {1, 2}
print(set_a.difference(set_b))     # Same result

# Symmetric Difference
print(set_a ^ set_b)                      # {1, 2, 5, 6}
print(set_a.symmetric_difference(set_b))  # Same result

Tags: python Data Types list Dictionary Set

Posted on Wed, 13 May 2026 08:54:53 +0000 by Fearsoldier