Python Datatypes – A Beginner’s Guide

Python Data Types

Python is a dynamically typed language, meaning you don’t need to explicitly declare variable types. The interpreter automatically determines the type based on the value assigned.

The primary built-in data types are

  • Numeric Type
  • Sequence Types
  • Mapping Types
  • Set Types
  • Boolean Type
  • Binary Types
  • None Type
Numeric Type

Python supports three distinct numeric types: integers, floating-point numbers, and complex numbers.

Integers

Integers (int) are whole numbers without decimal points. Python 3 has no limit on the length of integers, allowing you to work with arbitrarily large numbers. You can represent integers in decimal, binary (prefix 0b), octal (prefix 0o), or hexadecimal (prefix 0x) formats.

age = 25
population = 7_900_000_000  # Underscores for readability
binary_num = 0b1010  # Equals 10
hex_num = 0xFF  # Equals 255
Floating-point numbers (float)

Floating-point numbers (float) represent real numbers with decimal points. They follow the IEEE 754 double-precision standard, which means they have limitations in precision.

pi = 3.14159
scientific = 2.5e-3  # Equals 0.0025
negative = -45.67
Complex Numbers

Complex numbers (complex) consist of a real and imaginary part, written with a ‘j’ suffix for the imaginary component.

z = 3 + 4j
real_part = z.real  # Returns 3.0
imaginary_part = z.imag  # Returns 4.0
Sequence Types

Sequences are ordered collections of items that support indexing and slicing operations.

Strings

Strings (str) are immutable sequences of Unicode characters. You can create them using single, double, or triple quotes. Triple quotes allow multi-line strings and are commonly used for docstrings.

name = "Alice"
message = 'Hello, World!'
multiline = """This is a
multi-line string"""

# String operations
greeting = "Hello" + " " + "Python"  # Concatenation
repeated = "Ha" * 3  # Equals "HaHaHa"
length = len(name)  # Returns 5

Strings supports many methods including upper()lower()strip()split()replace()find(), and format operations using f-strings.

email = "  USER@EXAMPLE.COM  "
cleaned = email.strip().lower()  # "user@example.com"

name = "Bob"
age = 30
formatted = f"{name} is {age} years old"
Lists

Lists (list) are mutable, ordered collections that can contain items of different types.

fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]

# List operations
fruits.append("orange")  # Add to end
fruits.insert(1, "mango")  # Insert at index
fruits.remove("banana")  # Remove by value
popped = fruits.pop()  # Remove and return last item
fruits.sort()  # Sort in place
reversed_fruits = fruits[::-1]  # Reverse using slicing
Tuples

Tuples (tuple) are immutable sequences, making them faster and more memory-efficient than lists.

coordinates = (10, 20)
single_item = (42,)  # Note the comma for single-item tuples
person = ("Alice", 28, "Engineer")

# Tuple unpacking
x, y = coordinates
name, age, profession = person
Range

Range (range) generates sequences of numbers efficiently without storing all values in memory.

numbers = range(5)  # 0, 1, 2, 3, 4
evens = range(0, 10, 2)  # 0, 2, 4, 6, 8
countdown = range(10, 0, -1)  # 10, 9, 8, ..., 1

for i in range(3):
    print(i)
Set Types

Sets are unordered collections of unique elements, perfect for membership testing and eliminating duplicates.

Sets

Sets (set) are mutable and support mathematical set operations like union, intersection, and difference.

fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 3, 4}  # Duplicates removed automatically

# Set operations
fruits.add("orange")
fruits.remove("banana")
fruits.discard("grape")  # Won't raise error if not found

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2  # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2  # {3, 4}
difference = set1 - set2  # {1, 2}
Frozensets

Frozensets (frozenset) are immutable versions of sets, allowing them to be used as dictionary keys or elements of other sets.

immutable_set = frozenset([1, 2, 3])
# immutable_set.add(4)  # Would raise AttributeError
Mapping Type
Dictionaries

Dictionaries (dict) store key-value pairs and provide fast lookups. Keys must be immutable types (strings, numbers, tuples), while values can be any type.

student = {
    "name": "Alice",
    "age": 22,
    "grades": [85, 90, 88]
}

# Accessing and modifying
student["major"] = "Computer Science"
age = student.get("age")  # Returns None if key doesn't exist
student.pop("grades")  # Remove and return value

# Iteration
for key, value in student.items():
    print(f"{key}: {value}")

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
Boolean Type
Boolean

Booleans (bool) represent truth values with only two possible values: True and False. They’re essential for control flow and logical operations.

is_active = True
is_admin = False

# Boolean operations
result = True and False  # False
result = True or False  # True
result = not True  # False

# Truthiness - these values evaluate to False
empty_list = []
empty_string = ""
zero = 0
none_value = None
None Type
None

None represents the absence of a value, similar to null in other languages

def find_user(user_id):
    # Returns None if user not found
    return None

result = find_user(123)
if result is None:
    print("User not found")
Binary Types
Bytes

Bytes (bytes) are immutable sequences of bytes, representing binary data.

data = b"Hello"
byte_array = bytes([65, 66, 67])  # b'ABC'
encoded = "Hello".encode('utf-8')
Bytearray

Bytearray (bytearray) is the mutable version of bytes.

mutable_bytes = bytearray(b"Hello")
mutable_bytes[0] = 72  # Change 'H' to 'h'

Type Conversion

Python allows explicit conversion between types using constructor functions.

# To integer
num = int("42")
floored = int(3.9)  # Returns 3

# To float
decimal = float("3.14")
float_num = float(10)

# To string
text = str(42)
string_list = str([1, 2, 3])

# To list
char_list = list("Hello")  # ['H', 'e', 'l', 'l', 'o']
number_list = list(range(5))

# To tuple
immutable = tuple([1, 2, 3])

# To set
unique = set([1, 2, 2, 3])  # {1, 2, 3}

Type Checking

You can check types at runtime using type() and isinstance().

x = 42
print(type(x))  # <class 'int'>

# isinstance() is preferred for type checking
if isinstance(x, int):
    print("x is an integer")

# Check against multiple types
if isinstance(x, (int, float)):
    print("x is numeric")

Worthwhile Books to learn Python from

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top