Python Data Types

By Seokhyeon Byun 5 min read

Note: This post is based on my old programming study notes when I taught myself.

Characteristic of Data in Python

All data in Python is represented by objects or by relations between objects. Every object has an identity, a type and a value.

Primitive Types

Numeric Types

  • Integer: Whole numbers (positive, negative, or zero)
  • Float: Real numbers including decimal points
# Integer examples
age = 25
temperature = -10
count = 0

# Float examples
price = 19.99
pi = 3.14159
scientific = 2.5e6  # 2,500,000

String Type

A sequence of characters. Use single quotes (”) or double quotation marks ("") to create strings.

# String examples
name = "John Doe"
message = 'Hello, World!'
multiline = """This is a
multiline string"""

# String operations
full_name = "John" + " " + "Doe"  # Concatenation
repeated = "Ha" * 3  # "HaHaHa"

Reference: Python String Methods Documentation

Boolean Type

True or False values.

is_student = True
is_graduated = False

# Important notes:
# - 0 equals False
# - 1 equals True
# - In Python, T and F must be capital

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

None Type

A single object that has a value ‘None’. It represents the absence of a value.

data = None
result = None

# Important: None is not the same as:
# - 0 (zero)
# - False
# - An empty string ""

Sequence Types

There are three different sequence types:

Immutable Sequences

  • String: "hello"
  • Tuples: Use ()
# Tuple examples
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (42,)  # Note the comma for single item

Mutable Sequences

  • Lists: Use []
# List examples
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4]]

Range Objects

# Range examples
numbers = range(10)        # 0 to 9
evens = range(0, 10, 2)    # 0, 2, 4, 6, 8
countdown = range(10, 0, -1)  # 10, 9, 8, ..., 1

Reference: Python Sequence Types Documentation


Data Type Conversion

Basic Conversions

  • int(): Convert to integer
  • float(): Convert to float (real number)
  • str(): Convert to string
# Integer conversion
num_str = "123"
num_int = int(num_str)  # 123
float_num = 3.14
int_from_float = int(float_num)  # 3 (truncated)

# Float conversion
int_num = 42
float_num = float(int_num)  # 42.0
str_num = "3.14"
float_from_str = float(str_num)  # 3.14

# String conversion
number = 42
str_num = str(number)  # "42"
boolean = True
str_bool = str(boolean)  # "True"

Advanced Conversions

# List, tuple, set conversions
string = "hello"
char_list = list(string)      # ['h', 'e', 'l', 'l', 'o']
char_tuple = tuple(string)    # ('h', 'e', 'l', 'l', 'o')
char_set = set(string)        # {'h', 'e', 'l', 'o'}

# Boolean conversion
bool(1)       # True
bool(0)       # False
bool("")      # False
bool("text")  # True
bool([])      # False
bool([1, 2])  # True

Useful Built-in Functions

String Methods

text = "  Hello World  "

# Case conversion
text.upper()     # "  HELLO WORLD  "
text.lower()     # "  hello world  "
text.title()     # "  Hello World  "

# Whitespace handling
text.strip()     # "Hello World"
text.lstrip()    # "Hello World  "
text.rstrip()    # "  Hello World"

# Search and replace
text.find("World")      # 8 (index of "World")
text.count("l")         # 3 (number of "l"s)
text.replace("World", "Python")  # "  Hello Python  "

# Splitting and joining
sentence = "apple,banana,orange"
fruits = sentence.split(",")     # ["apple", "banana", "orange"]
joined = "-".join(fruits)        # "apple-banana-orange"

List Methods

numbers = [1, 2, 3]

# Adding elements
numbers.insert(0, 0)    # [0, 1, 2, 3] (insert at index)
numbers.append(4)       # [0, 1, 2, 3, 4] (add to end)

# Removing elements
numbers.pop()           # Returns and removes 4: [0, 1, 2, 3]
numbers.pop(0)          # Returns and removes 0: [1, 2, 3]

General Built-in Functions

# Type checking
type(42)           # <class 'int'>
isinstance(42, int)  # True

# Length and size
len("hello")       # 5
len([1, 2, 3])     # 3

# Math functions
abs(-5)           # 5
max([1, 2, 3])    # 3
min([1, 2, 3])    # 1
sum([1, 2, 3])    # 6

# Input/Output
name = input("Enter your name: ")  # Get user input
print("Hello,", name)              # Print output

Reference: Python Built-in Functions Documentation


Type Checking and Validation

# Check data types
data = 42
print(type(data))           # <class 'int'>
print(isinstance(data, int))  # True

# Multiple type checking
def process_data(value):
    if isinstance(value, (int, float)):
        return value * 2
    elif isinstance(value, str):
        return value.upper()
    else:
        return None

# Type validation example
def safe_divide(a, b):
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
        return "Error: Both arguments must be numbers"
    if b == 0:
        return "Error: Cannot divide by zero"
    return a / b

Common Pitfalls and Tips

Mutable vs Immutable

# Immutable - creates new object
text = "hello"
text.upper()  # Returns "HELLO" but doesn't change original
print(text)   # Still "hello"

# Mutable - modifies existing object
numbers = [1, 2, 3]
numbers.append(4)  # Modifies the original list
print(numbers)     # [1, 2, 3, 4]

Type Conversion Edge Cases

# Be careful with these conversions
int("3.14")     # ValueError: invalid literal
int(float("3.14"))  # 3 (correct way)

# String to boolean is always True (except empty string)
bool("False")   # True (string "False" is truthy)
bool("")        # False (empty string is falsy)

Memory Efficiency

# For large numeric ranges, use range() instead of list
# Memory efficient
for i in range(1000000):
    pass

# Memory intensive
for i in list(range(1000000)):  # Creates list in memory
    pass