Skip to main content

Command Palette

Search for a command to run...

Understanding Python Data Types: A Complete Overview

Published
•5 min read•View as Markdown
K

I'm a passionate and detail-oriented technical writer that specializes in translating technical topics and products into accessible insights. Experienced in crafting easy-to-understand technical blog posts that break down complex topics for both beginners and enthusiasts. I apply strong research and organizational skills to create educational resources that simplify complex topics with SEO optimization in mind. I am passionate about AI and Web3.

If you're completely new to Python, this guide will introduce you to the core concept of Python data types. For seasoned programmers, it's a quick refresher on the fundamentals. So grab a cup of coffee and let's dive into the world of Python data types!

Table of Contents:

  • Introduction

  • Why Variables Are Not Considered Data Types

  • How to Get the Data Type of an Object

  • How to Set an Object to a Specific Data Type

  • Importance of Data Types

  • Python Data Types:

    • Numeric Data Types

    • Sequence Data Types

    • Binary Data Types

    • Mapping Data Types

    • Boolean Data Types

    • Set Data Types

    • Custom-Defined Data Types

  • Conclusion


Introduction:

In Python, data types define the kind of value that can be stored in an object. They dictate the kinds of operations that can be performed on that object, such as arithmetic, string manipulation, or logical comparisons. By constraining the types of data an object can hold, data types prevent errors and ensure your code runs smoothly.

Think of data types like different types of containers:

  • A weaved sack might hold solid objects but would struggle with liquid or powdered items.

  • A polythene sack is perfect for liquid materials but unsuitable for powders.

  • A carton might be ideal for storing powders but not for liquids.

Understanding data types is crucial for avoiding errors—just as it would be a mistake to pour liquid into a carton not meant for it, mismatching data types can lead to bugs in your program.


Why Variables Are Not Considered Data Types:

Variables in Python are like labels. They store values of different data types, but they do not define the type themselves. When you assign a value to a variable, you're declaring that variable.

For example:

name = "Kelvin"  # string
age = 25         # integer
cgpa = 4.35      # float
likes = ["fruit", "clothes", "writing"]  # list

Here, the variables name, age, cgpa, and likes are storing different types of data, but the variable itself doesn’t define the type—Python handles that automatically.


How to Get the Data Type of an Object:

In Python, the type() function is used to determine the data type of an object. This is especially useful if you're unsure what kind of data you're dealing with.

Examples:

print(type(name))  # Output: <class 'str'>
print(type(age))   # Output: <class 'int'>
print(type(cgpa))  # Output: <class 'float'>
print(type(likes)) # Output: <class 'list'>

How to Set an Object to a Specific Data Type:

Python is a dynamically typed language, meaning that variables can change types at runtime. You can convert an object’s data type using built-in functions like int(), float(), str(), etc.

For example, converting a list to a tuple:

likes = ["fruit", "clothes", "writing"]  # list
likes_tuple = tuple(likes)               # now a tuple
print(type(likes_tuple))                 # Output: <class 'tuple'>

Importance of Data Types:

  1. Efficient Memory Management: Assigning the correct data type ensures you don’t waste memory. For example, int takes less space than a list or float.

     a = 1          # int
     b = [1, 2, 3]  # list
    
  2. Data Integrity: Using the correct data type ensures that your variables hold valid data. For example, assigning a string to a variable that is meant to hold a number can lead to errors.

     a = 12      # integer
     b = "12"    # string
    
  3. Valid Operations: Using the right data type allows you to perform valid operations. For instance, you can perform arithmetic on numbers but not on strings.

     a = 12
     b = a * 5   # valid arithmetic
     c = "ade"
     d = c + "leke"  # string concatenation
     print(d)        # Output: adeleke
    
  4. Error Prevention: Understanding data types helps prevent runtime errors, such as trying to divide a string by an integer.


Python Data Types:

Numeric Data Types:

Python supports three main numeric types: int, float, and complex.

  • Integers: Whole numbers, positive or negative.

      a = 23
      b = -23
      c = 0
    
  • Floats: Numbers with decimal points.

      a = 23.5
      b = -23.5
    
  • Complex Numbers: Numbers with both real and imaginary parts, denoted by j.

      a = 3 + 5j
      b = -4j
    

Sequence Data Types:

Sequence data types store collections of items and support operations like indexing, slicing, and concatenation.

  • String: An immutable sequence of characters.

      name = "Kelvin"
    
  • List: A mutable sequence that can contain items of different types.

      data = ["kelvin", 13, 3.2, ["age", "date"]]
    
  • Tuple: An immutable sequence, meaning once created, it cannot be changed.

      data = ("kelvin", 13, 3.2, ["age", "date"])
    
  • Range: A sequence of numbers, often used in loops.

      num_range = range(1, 10)
      for i in num_range:
          print(i)  # Outputs numbers 1 through 9
    

Binary Data Types:

Binary data types store raw binary data, often used for file handling or network data.

  • Bytes: An immutable sequence of bytes.

      first = b'This is a byte object'
      second = bytes([12, 14, 15])
    
  • Bytearray: A mutable sequence of bytes, which can be modified.

      first = bytearray([1, 67, 78])
      first[0] = 23  # Mutating the bytearray
    
  • Memoryview: A way to access the memory of an existing binary object without copying it.

      first = b'hello world'
      mv = memoryview(first)
      print(mv[0])  # Output: 104 (ASCII for 'h')
    

Conclusion:

Understanding Python’s data types is crucial to writing efficient, error-free code. Data types ensure that you are using the right kind of object for the right operation, help manage memory effectively, and prevent bugs from creeping into your programs. Whether you are a beginner or an expert, mastering Python’s data types is the first step towards mastering the language itself.