In this tutorial, we will explore the fundamental data types available in Python. Understanding these data types is crucial for any programmer as they form the building blocks of more complex data structures and algorithms. Whether you're a beginner or an experienced developer, having a solid grasp of Python's data types will significantly enhance your coding skills.
Python provides several built-in data types that allow you to store and manipulate different kinds of data. These data types can be categorized into two main groups: primitive (or basic) data types and composite (or structured) data types. In this section, we'll cover the following primitive data types:
int: Integer numbersfloat: Floating-point numberscomplex: Complex numbersstr: Stringsbool: Boolean valuesAnd the following composite data types:
list: Ordered collections of itemstuple: Immutable ordered collections of itemsset: Unordered collections of unique itemsdict: Key-value pairsWe'll also discuss how to check the type of a variable using the type() function and how to perform type checking with the isinstance() function.
int)An integer is a whole number without any decimal points. Python's int type can handle arbitrarily large integers, limited by available memory.
1# Example of int data type2a = 423b = -10045print("Type of a:", type(a))6print("Type of b:", type(b))
Type of a: <class 'int'> Type of b: <class 'int'>
float)A floating-point number is a decimal number that can have fractional parts. Python's float type follows the IEEE 754 standard for double-precision floating-point numbers.
1# Example of float data type2x = 3.143y = -0.00145print("Type of x:", type(x))6print("Type of y:", type(y))
Type of x: <class 'float'> Type of y: <class 'float'>
complex)A complex number has a real part and an imaginary part, represented as a + bj. Python's complex type is used to handle such numbers.
1# Example of complex data type2z = 2 + 3j3w = -1.5 - 0.5j45print("Type of z:", type(z))6print("Type of w:", type(w))
Type of z: <class 'complex'> Type of w: <class 'complex'>
str)A string is a sequence of characters enclosed in quotes (single, double, or triple). Strings are immutable, meaning they cannot be changed after creation.
1# Example of str data type2name = "Alice"3greeting = 'Hello, World!'45print("Type of name:", type(name))6print("Type of greeting:", type(greeting))
Type of name: <class 'str'> Type of greeting: <class 'str'>
bool)A boolean value can be either True or False. Booleans are often used in conditional statements to control the flow of a program.
1# Example of bool data type2is_raining = True3has_umbrella = False45print("Type of is_raining:", type(is_raining))6print("Type of has_umbrella:", type(has_umbrella))
Type of is_raining: <class 'bool'> Type of has_umbrella: <class 'bool'>
list)A list is an ordered collection of items that can be of different types. Lists are mutable, meaning you can modify them after creation.
1# Example of list data type2fruits = ["apple", "banana", "cherry"]3numbers = [1, 2, 3, 4, 5]45print("Type of fruits:", type(fruits))6print("Type of numbers:", type(numbers))
Type of fruits: <class 'list'> Type of numbers: <class 'list'>
tuple)A tuple is similar to a list, but it is immutable. Once created, the contents of a tuple cannot be changed.
1# Example of tuple data type2coordinates = (10, 20)3colors = ("red", "green", "blue")45print("Type of coordinates:", type(coordinates))6print("Type of colors:", type(colors))
Type of coordinates: <class 'tuple'> Type of colors: <class 'tuple'>
set)A set is an unordered collection of unique items. Sets are mutable and support operations like union, intersection, and difference.
1# Example of set data type2unique_numbers = {1, 2, 3, 4, 5}3vowels = {'a', 'e', 'i', 'o', 'u'}45print("Type of unique_numbers:", type(unique_numbers))6print("Type of vowels:", type(vowels))
Type of unique_numbers: <class 'set'> Type of vowels: <class 'set'>
dict)A dictionary is a collection of key-value pairs where each key is unique. Dictionaries are mutable and allow for fast lookups.
1# Example of dict data type2person = {"name": "Alice", "age": 30, "city": "New York"}3prices = {"apple": 1.2, "banana": 0.5, "cherry": 2.0}45print("Type of person:", type(person))6print("Type of prices:", type(prices))
Type of person: <class 'dict'> Type of prices: <class 'dict'>
NoneType is a special data type that represents the absence of a value or a null value.
1# Example of NoneType2nothing = None34print("Type of nothing:", type(nothing))
Type of nothing: <class 'NoneType'>
type() and isinstance()type()The type() function returns the type of an object.
1# Example of using type()2a = 103b = "Hello"4c = [1, 2, 3]56print("Type of a:", type(a))7print("Type of b:", type(b))8print("Type of c:", type(c))
Type of a: <class 'int'> Type of b: <class 'str'> Type of c: <class 'list'>
isinstance()The isinstance() function checks if an object is an instance of a specific type or a tuple of types.
1# Example of using isinstance()2a = 103b = "Hello"4c = [1, 2, 3]56print("Is a an int?", isinstance(a, int))7print("Is b a str?", isinstance(b, str))8print("Is c a list or tuple?", isinstance(c, (list, tuple)))
Is a an int? True Is b a str? True Is c a list or tuple? True
Let's create a simple program that checks the types of various variables and performs some basic operations.
1# Practical example: Type checking and operations2def describe_variable(var):3var_type = type(var).__name__4print(f"The variable is of type {var_type}.")56def main():7num1 = 428num2 = 3.149name = "Alice"10is_student = True11grades = [90, 85, 78]12person = {"name": "Bob", "age": 25}1314describe_variable(num1)15describe_variable(num2)16describe_variable(name)17describe_variable(is_student)18describe_variable(grades)19describe_variable(person)2021if __name__ == "__main__":22main()
The variable is of type int. The variable is of type float. The variable is of type str. The variable is of type bool. The variable is of type list. The variable is of type dict.
| Data Type | Description |
|---|---|
int | Integer numbers |
float | Floating-point numbers |
complex | Complex numbers |
str | Strings |
bool | Boolean values |
list | Ordered collections of items |
tuple | Immutable ordered collections of items |
set | Unordered collections of unique items |
dict | Key-value pairs |
NoneType | Absence of a value |
In the next tutorial, we will dive deeper into numbers and mathematical operations in Python. We'll explore arithmetic operators, number formatting, and more advanced numerical functions. Stay tuned!
Tip
Understanding data types is essential for effective programming. Always ensure that your variables are of the correct type to avoid unexpected errors.
Warning
Be cautious when using mutable data types like lists and dictionaries, as they can be changed in place without creating a new object.
Note
The type() function returns the exact type of an object, while isinstance() checks for compatibility with a specified type or tuple of types.