Python Programming Guide

Python Data Types: Guide With Examples and Uses

Python automatically identifies the type of data you assign to a variable, whether it is an integer, string, list, or another type. This feature is known as dynamic typing and makes Python easier to use than languages like C or Java.

However, understanding data types is essential to avoid common coding errors. This guide explains Python’s built-in data types with practical code examples and shows how to convert between types when needed.

Python Numeric Data Types

Python provides three numeric data types: int, float, and complex. These types allow you to work with whole numbers, decimal values, and complex mathematical calculations.

Integer (int)

The int data type represents whole numbers without decimal points. It supports positive values, negative values, and zero. Python integers can handle very large numbers, depending on the available system memory.

Working with Integers

students = 30
balance = -500
score = 0

print("Students:", students)
print("Balance:", balance)
print("Score:", score)
print("Data Type:", type(students))

Output:

Students: 30
Balance: -500
Score: 0
Data Type: <class 'int'>

Floating-Point Numbers (float)

The float data type is used to represent numbers that contain decimal values. It is useful for calculations involving prices, measurements, percentages, and scientific data. Python typically stores floats using 64-bit double precision, providing approximately 15–16 significant decimal digits.

# Working with Float Values
product_price = 49.95
height = 5.75
discount = -1.25

print("Product Price:", product_price)
print("Height:", height)
print("Discount:", discount)
print("Data Type:", type(product_price))

Output:

Product Price: 49.95
Height: 5.75
Discount: -1.25
Data Type: <class 'float'>

Floating-point calculations can sometimes produce slightly unexpected results. For instance, adding 0.1 and 0.2 may return 0.30000000000000004 instead of 0.3. This occurs because binary floating-point numbers cannot represent some decimal values exactly. For calculations requiring precise decimal results, Python provides the decimal module.

Complex Numbers (complex)

The complex data type represents numbers with both real and imaginary components. While mathematics commonly uses i for the imaginary unit, Python uses j to represent it in code.

# Working with Complex Numbers
number = 4 + 6j
print("Number:", number)
print("Real Component:", number.real)
print("Imaginary Component:", number.imag)
print("Data Type:", type(number))

Output:

Number: (4+6j)
Real Component: 4.0
Imaginary Component: 6.0
Data Type: <class 'complex'>

Sequence Data Types in Python

Sequence data types store multiple elements in a specific order. They allow you to retrieve individual items using indexes and extract portions of data through slicing. Python’s primary sequence types include strings, lists, and tuples.

String (str)

A string represents text and can be defined using single quotes, double quotes, or triple quotes for multiple lines. Strings are immutable, so their characters cannot be modified directly after creation. Any operation that changes the text produces a new string instead.

# Exploring String Operations
first_name = "Aarav"
last_name = 'Sharma'
message = """Welcome to
Python programming!"""
print("Full Name:", first_name + " " + last_name)
print("Repeated Text:", "Hi! " * 2)
print("Message Length:", len(first_name))
print("First Letter:", first_name[0])
print("Substring:", first_name[1:4])

Output:

Full Name: Aarav Sharma
Repeated Text: Hi! Hi!
Message Length: 5
First Letter: A
Substring: ara

List (list)

A list is a versatile Python collection that stores multiple values in a single variable. It can contain different data types, and its elements can be added, deleted, or updated whenever needed. Since lists are mutable, their contents can change after creation.

# Exploring List Operations
colors = ["red", "green", "blue", "yellow"]
print("Initial list:", colors)
print("First element:", colors[0])
print("Selected items:", colors[1:3])
colors[1] = "purple"
colors.append("orange")
colors.remove("blue")
print("Updated list:", colors)

Output:

Initial list: ['red', 'green', 'blue', 'yellow']
First element: red
Selected items: ['green', 'blue']
Updated list: ['red', 'purple', 'yellow', 'orange']

To locate an element within a list, you can use Python’s indexing methods to identify its position and retrieve the required value.

Tuple (tuple)

A tuple is an ordered collection similar to a list, but it uses parentheses instead of square brackets. Its main characteristic is immutability, which means you cannot modify, insert, or delete individual elements after creating it. Tuples are suitable for storing fixed information, such as geographical coordinates or weekday names.

# Exploring Tuple Operations
days = ("Monday", "Tuesday", "Wednesday", "Thursday")
print("Tuple values:", days)
print("First element:", days[0])
print("Selected elements:", days[1:3])
print("Total elements:", len(days))
# Tuples do not allow item modification:
# days[0] = "Sunday"  # Raises a TypeError

Output:

Tuple values: ('Monday', 'Tuesday', 'Wednesday', 'Thursday')
First element: Monday
Selected elements: ('Tuesday', 'Wednesday')
Total elements: 4

Differences Between Lists and Tuples

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Modifiable Yes No
Performance Generally slightly slower Generally slightly faster
Memory usage Usually higher Usually lower
Common use Collections that change Fixed collections of values

Set Data Type in Python

A set is a collection that stores unique elements without maintaining a guaranteed order. When duplicate values are added, Python retains only one instance of each value. Sets are useful for eliminating repeated items and performing mathematical operations, such as finding common or combined elements.

# Working with Sets
values = {2, 4, 6, 4, 8, 2, 10}
print("Unique values:", values)
print("Number of elements:", len(values))
values.add(12)
values.discard(6)
print("Modified set:", values)
# Performing set operations
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print("Combined elements:", x | y)
print("Common elements:", x & y)

Output:

Unique values: {2, 4, 6, 8, 10}
Number of elements: 5
Modified set: {2, 4, 8, 10, 12}
Combined elements: {10, 20, 30, 40, 50, 60}
Common elements: {40, 30}

Sets do not support indexing because their elements have no guaranteed positional order. If you need to preserve insertion order while removing duplicates, you can use dict.fromkeys() or implement a list-based approach.

Mapping Data Type: Dictionary (dict)

A Python dictionary organizes information into key-value pairs, allowing you to retrieve data using unique keys rather than numerical positions. Dictionaries provide efficient lookups and let you store different types of values. Keys must be hashable, commonly strings, numbers, or tuples containing hashable elements, while values can contain any data type.

# Working with Dictionaries
employee = {"name": "Riya", "age": 24, "department": "IT"}
print("Employee Details:", employee)
print("Employee Name:", employee["name"])
employee["city"] = "Delhi"
employee["age"] = 25
del employee["department"]
print("Updated Details:", employee)

Output:

Employee Details: {'name': 'Riya', 'age': 24, 'department': 'IT'}
Employee Name: Riya
Updated Details: {'name': 'Riya', 'age': 25, 'city': 'Delhi'}

Boolean Data Type in Python

The Boolean type (bool) represents one of two possible values: True or False. It is commonly used in conditional statements, logical expressions, and comparison operations to determine whether a condition is satisfied. In Python, Boolean values also behave like integers, where True equals 1 and False equals 0.

# Exploring Boolean Values
is_logged_in = True
payment_complete = False
print("Logged In:", is_logged_in)
print("Payment Complete:", payment_complete)
# Checking Conditions
marks = 85
print("Marks above 50:", marks > 50)
print("Marks equal to 40:", marks == 40)
print("Data Type:", type(is_logged_in))

Output:

Logged In: True
Payment Complete: False
Marks above 50: True
Marks equal to 40: False
Data Type: <class 'bool'>

Binary Data Types: bytes and bytearray

Python provides binary data types for handling information in the form of bytes. They are commonly used when processing files, transferring network data, or working with images and other binary content. The bytes type is immutable, whereas bytearray allows you to modify individual bytes after creation.

# Exploring Binary Data Types
file_data = bytes([80, 121, 116, 104, 111, 110])
print("Bytes object:", file_data)
editable_data = bytearray([80, 121, 116, 104, 111, 110])
editable_data[0] = 67
print("Updated bytearray:", editable_data)
print("Bytes Type:", type(file_data))
print("Bytearray Type:", type(editable_data))

Output:

Bytes object: b'Python'
Updated bytearray: bytearray(b'Cython')
Bytes Type: <class 'bytes'>
Bytearray Type: <class 'bytearray'>

Although these types may not be necessary for basic Python programs, they are valuable when handling binary files, network communication, and API data.

How to Identify Data Types in Python

The type() function lets you determine the data type of a variable. It is helpful for checking stored values, debugging code, and verifying how Python classifies different objects.

# Checking Different Variable Types
count = 12
rate = 7.25
city = "Mumbai"
numbers = [10, 20, 30]
coordinates = (5, 8)
details = {"name": "Aman"}
available = False
print(type(count))
print(type(rate))
print(type(city))
print(type(numbers))
print(type(coordinates))
print(type(details))
print(type(available))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'bool'>

You can also use isinstance() to verify whether a value belongs to a particular data type. The function returns True or False, making it useful for checking conditions and validating input.

count = 12
print(isinstance(count, int))   # True
print(isinstance(count, str))   # False

Both functions are useful for understanding variable types and writing Python code that handles data correctly.

Choosing the Right Python Data Type

Understanding Python data types is important, but selecting the appropriate type for a particular task is equally essential. The following table summarizes common use cases and explains when each data type is most suitable.

Use Case Recommended Type Reason
Counting items, age, or marks int Represents whole numbers
Prices, weights, or distances float Supports decimal values
Scientific or engineering calculations complex Represents real and imaginary components
Names, sentences, or messages str Designed for text processing
Data that needs frequent updates list Allows adding, removing, and modifying elements
Fixed groups of related values tuple Prevents changes to individual elements
Removing duplicate values set Stores unique elements and supports set operations
Organizing information by identifiers dict Stores and retrieves key-value pairs efficiently
Conditions and logical checks bool Represents True or False
Binary files and network content bytes / bytearray Handles raw binary information

Converting Data Types in Python

Type conversion involves changing a value from one data type to another. For example, you may need to transform text input into a number for calculations or convert a numeric value into a string for display. Python supports two methods: implicit conversion, which happens automatically, and explicit conversion, which you perform manually.

Automatic Type Conversion

Implicit conversion occurs when Python automatically adjusts a value’s data type during an operation. For example, when an integer and a floating-point number are combined, Python converts the integer into a float before completing the calculation.

# Demonstrating Automatic Conversion
whole_number = 15
decimal_number = 4.5

total = whole_number + decimal_number

print("Whole Number:", whole_number, "->", type(whole_number))
print("Decimal Number:", decimal_number, "->", type(decimal_number))
print("Total:", total, "->", type(total))

Output:

Whole Number: 15 -> <class 'int'>
Decimal Number: 4.5 -> <class 'float'>
Total: 19.5 -> <class 'float'>

In this example, Python returns a float because one of the values is a floating-point number. However, automatic conversion does not work with every combination of types. For instance, adding a string directly to an integer raises a TypeError because Python cannot determine the intended operation.

Manual Type Conversion in Python

Explicit conversion allows you to change a value’s data type using Python’s built-in functions. This approach is useful when automatic conversion is unavailable or when you need a specific type for an operation.

Function Purpose Example
int() Converts a value to an integer, removing the decimal part of a float int(8.9) → 8
float() Changes a number into a floating-point value float(6) → 6.0
str() Converts a value into text str(250) → "250"
bool() Evaluates a value as True or False bool(0) → False
list() Creates a list from an iterable list("dog") → ['d', 'o', 'g']
tuple() Creates a tuple from an iterable tuple([3, 4]) → (3, 4)
set() Creates a set containing unique elements set([2, 2, 5]) → {2, 5}
dict() Builds a dictionary from key-value pairs dict([("x", 10)]) → {'x': 10}
ord() Returns the Unicode code point of a character ord('B') → 66
chr() Returns the character represented by a Unicode code point chr(66) → 'B'

Note: Not every value can be converted successfully. For example, int(“hello”) raises a ValueError because the string does not represent a valid integer.

Converting Values with int(), float(), and str()

Python’s int(), float(), and str() functions are among the most commonly used tools for converting data types. They help you perform calculations with numeric values, handle decimal numbers, and turn values into text when needed.

# Converting Values into Different Types
cost = "200"
items = 4
amount = int(cost) * items
print("Total Amount:", amount)
# Converting a float into an integer
weight = 67.8
print("Integer Weight:", int(weight))
# Converting Boolean values into integers
print("True as Integer:", int(True))
print("False as Integer:", int(False))

Output:

Total Amount: 800
Integer Weight: 67
True as Integer: 1
False as Integer: 0

Keep in mind that int() truncates the decimal portion instead of rounding the value. For example, int(67.8) returns 67, not 68.

The float() and str() functions are also essential for converting values between numeric and text formats.

Converting Values to Floating-Point Numbers

Use float() to transform integers or valid numeric strings into decimal numbers.

# Converting Values into Floats
count = 35
decimal_text = "6.25"
print("Integer to Float:", float(count))
print("String to Float:", float(decimal_text))
print("Result Type:", type(float(count)))

Output:

Integer to Float: 35.0
String to Float: 6.25
Result Type: <class 'float'>

Converting Values into Strings

The str() function converts values into text, making it easier to combine numbers and other data with messages.

# Converting Values into Strings
year = 2026
rating = 4.8
is_available = True
print("Year: " + str(year))
print("Rating: " + str(rating))
print("Availability: " + str(is_available))
# Using an integer directly with a string causes an error:
# print("Year: " + year)

Output:

Year: 2026
Rating: 4.8
Availability: True

Without str(), combining a string and an integer with the + operator raises a TypeError. Alternatively, you can use an f-string, such as f"Year: {year}", which automatically formats the value within the text.

Converting Values to Booleans with bool()

The bool() function converts a value into either True or False. In Python, zero, empty collections, empty strings, and None are considered false, while most other values are evaluated as true.

# Checking Boolean Conversion
print("Zero:", bool(0))
print("Positive Number:", bool(42))
print("Empty Text:", bool(""))
print("Non-empty Text:", bool("Python"))
print("Empty List:", bool([]))
print("List with Values:", bool([3, 5]))
print("None Value:", bool(None))

Output:

Zero: False
Positive Number: True
Empty Text: False
Non-empty Text: True
Empty List: False
List with Values: True
None Value: False

These rules are useful when checking whether a variable contains a meaningful value or when writing conditional statements. Keep in mind that strings such as “False” are considered True because they are not empty.

Transforming Data Between Collection Types

Python allows you to convert between collection types, including lists, tuples, sets, and dictionaries. These conversions are useful when organizing data, eliminating duplicate values, or preparing information for a function that requires a particular structure.

# Converting Between Collection Types
word = "Coding"
letters = list(word)
print("String to List:", letters)
values = [2, 4, 2, 6, 8, 4]
distinct_values = set(values)
print("List to Set:", distinct_values)
entries = (("city", "Delhi"), ("year", 2026))
details = dict(entries)
print("Pairs to Dictionary:", details)

Output:

String to List: ['C', 'o', 'd', 'i', 'n', 'g']
List to Set: {2, 4, 6, 8}
Pairs to Dictionary: {'city': 'Delhi', 'year': 2026}

These conversions make it easier to manipulate collections and choose the most suitable structure for your data. Remember that sets remove duplicates and do not guarantee element order.

Character and Unicode Conversion Using ord() and chr()

Python provides ord() and chr() to convert between characters and their corresponding Unicode code points. The ord() function returns a character’s numeric code, while chr() converts a valid code point back into a character. These functions are useful for character manipulation, encoding exercises, and basic encryption examples.

# Exploring Character Conversion
symbol = 'B'
unicode_value = ord(symbol)
print(f"ord('{symbol}') = {unicode_value}")
character = chr(unicode_value)
print(f"chr({unicode_value}) = '{character}'")
# Displaying character codes
for letter in "World":
    print(f"  '{letter}' -> {ord(letter)}")

Output:

ord('B') = 66
chr(66) = 'B'
  'W' -> 87
  'o' -> 111
  'r' -> 114
  'l' -> 108
  'd' -> 100

Converting Between Number Systems: Binary, Octal, and Hexadecimal

Python’s int() function accepts a second argument that specifies the number system’s base. This allows you to convert binary (base 2), octal (base 8), and hexadecimal (base 16) strings into decimal integers. To convert integers back into these formats, Python provides the bin(), oct(), and hex() functions.

# Converting Number Systems
binary_value = "1100"
octal_value = "24"
hex_value = "2F"
print("Binary to Integer:", int(binary_value, 2))
print("Octal to Integer:", int(octal_value, 8))
print("Hexadecimal to Integer:", int(hex_value, 16))
# Converting an Integer into Different Bases
value = 31
print(f"\n{value} in Binary: {bin(value)}")
print(f"{value} in Octal: {oct(value)}")
print(f"{value} in Hexadecimal: {hex(value)}")

Output:

Binary to Integer: 12
Octal to Integer: 20
Hexadecimal to Integer: 47

31 in Binary: 0b11111
31 in Octal: 0o37
31 in Hexadecimal: 0x1f

Python includes prefixes in the output to identify each number system: 0b for binary, 0o for octal, and 0x for hexadecimal.

Converting Input Values into Numbers

One common mistake for Python beginners is forgetting that input() always returns a string, even when someone enters a numeric value. To perform calculations with user input, you must convert the string into an appropriate numeric type, such as int or float.

# Converting Input Strings into Numbers
age_text = "30"  # Example of input() data
# Adding a number directly to age_text would raise a TypeError
age = int(age_text)
future_age = age + 1
print(f"Your age is {age}. Next year, you will be {future_age}.")
# Converting decimal input for calculations
cost_text = "24.50"
cost = float(cost_text)
tax_amount = cost * 0.10
print(f"Cost: ${cost:.2f}, Tax: ${tax_amount:.2f}, Total: ${cost + tax_amount:.2f}")

Output:

Your age is 30. Next year, you will be 31.
Cost: $24.50, Tax: $2.45, Total: $26.95

Converting input values before performing arithmetic prevents type-related errors and ensures calculations work as expected. Keep in mind that invalid numeric strings, such as “hello”, will raise a ValueError when passed to int() or float().

Final Thoughts

Python’s built-in data types provide the foundation for writing effective programs. Integers and floats handle numeric values, strings manage text, lists and tuples organize collections, dictionaries store key-value pairs, sets maintain unique elements, and Booleans support logical decisions. Understanding these types and learning how to convert between them will help you avoid common programming errors.

Key Takeaways:

  • Python uses dynamic typing to determine variable types automatically, but understanding those types remains essential.
  • Lists allow modifications, whereas tuples keep their elements unchanged. Choose the appropriate collection for your needs.
  • Dictionaries organize information into key-value pairs and are widely used in Python applications.
  • The input() function returns a string, so use int() or float() before performing numerical calculations.
  • Implicit conversion happens automatically in compatible operations, while explicit conversion uses functions such as int(), str(), and float().
  • The type() function helps identify variable types and troubleshoot type-related errors.

After learning the fundamentals of data types, you can apply them to practical programming tasks involving loops, conditions, and collections. Building small projects and practising with different data types will help strengthen your understanding.

Campus Academic Help supports students in developing their programming knowledge, understanding Python concepts, and working through challenging coding problems. Regular practice and a clear understanding of these fundamentals will help you progress toward writing more efficient and reliable Python programs.

Frequently Asked Questions About Python Data Types

1. What are the different built-in data types in Python?

Python includes several built-in data types, such as numeric types (int, float, complex), sequence types (str, list, tuple), mapping types (dict), sets (set), Boolean values (bool), and binary types (bytes, bytearray). Use the type() function to identify a variable’s data type.

2. How are lists and tuples different in Python?

Lists and tuples both hold ordered collections of items, but they differ in whether their contents can be modified. Lists are mutable, allowing you to add, delete, or update elements. Tuples are immutable, meaning their elements cannot be changed after creation. Choose lists for changeable data and tuples for fixed collections.

3. What does type conversion mean in Python?

Type conversion means changing a value from one data type to another. Python can perform automatic conversions in certain operations, such as converting an integer to a float during arithmetic. For manual conversion, use functions like int(), float(), and str().

4. Why does Python’s input() function return a string?

The input() function treats everything entered by a user as text because it cannot automatically determine whether the input represents a number, a name, or another value. If you need to perform calculations with numeric input, convert it using int() or float() first.

5. What distinguishes implicit conversion from explicit conversion in Python?

Implicit conversion occurs automatically when Python converts a value to a compatible data type during an operation, such as converting an integer to a float. Explicit conversion requires you to specify the desired type using functions like int(), float(), or str().

6. How can I determine a variable’s data type in Python?

You can use type(variable) to identify a variable’s exact type. Alternatively, isinstance(variable, int) checks whether a value belongs to a particular type. The type() function is useful for inspecting values, while isinstance() is especially helpful when validating types in conditional statements.

#
+1-888-945-5705 Order Now
Call Us: +1-888-945-5705