Python Data Types

Master Python data types, the core of AI & Machine Learning development. Understand dynamic typing and variable instances for efficient data handling in Python.

1.2 Python Data Types

Python data types are fundamental building blocks that define the kind of data a variable can hold and the operations that can be performed on it. Python is dynamically typed, meaning the data type of a variable is determined automatically at runtime based on the value assigned to it. This contrasts with statically typed languages where types are declared explicitly.

All data types in Python are implemented as classes, and variables are instances of these classes.

Core Concepts

  • Dynamic Typing: Python infers the type of a variable at runtime.

  • Type Determination: The type is set based on the assigned value.

  • Operations: Data types dictate which operations are valid.

Types of Data Types in Python

Python offers a rich set of built-in data types to handle various kinds of data efficiently. These can be broadly categorized as follows:

1. Numeric Data Types

These are used to store numerical values.

  • int: Integer numbers (whole numbers, positive or negative, without decimals).

    • Example: var1 = 42

  • float: Real numbers with decimal points.

    • Example: var3 = 7.891

  • complex: Numbers with a real and an imaginary part, denoted by j or J.

    • Example: var4 = 4+2j

  • bool: Boolean values, representing either True or False. Booleans are a subtype of integers, where True is equivalent to 1 and False to 0.

    • Example: var2 = False

Examples of Numeric Values:

| Integer | Float | Complex | | :------ | :------ | :-------- | | 25 | 0.0 | 2.71j | | 123 | 12.34 | 12.j | | -5 | -45.67| -3.45+0j| | 0x1F | 19.0 | 6.02e23j| | -0x3C | -8.75e+10| 1.23j |

2. Text Data Type

  • str (String): Represents textual data enclosed in single (' ') or double (" ") quotes. Strings are immutable sequences.

    Example:

    title = "Python Programming"
    message = 'Welcome to the tutorial!'
    

    Accessing Characters:

    print(title[0])  # Output: P
    print(title[-1]) # Output: g
    

3. Sequence Data Types

These are ordered collections of items, allowing elements to be accessed by their index.

  • list (Mutable Sequence): An ordered, changeable collection of items. Elements can be of different data types. Lists are defined using square brackets [].

    • Example:

      colors = ["red", "green", "blue"]
      colors[1] = "yellow" # Modifying an element
      print(colors)        # Output: ['red', 'yellow', 'blue']
      
  • tuple (Immutable Sequence): An ordered, unchangeable collection of items. Once created, the elements of a tuple cannot be modified. Tuples are defined using parentheses ().

    • Example:

      coordinates = (10, 20)
      print(coordinates[0]) # Output: 10
      # coordinates[0] = 5 # This would raise a TypeError
      
  • range: Represents an immutable sequence of numbers, often used in for loops. It's not stored in memory as a full list, making it memory-efficient.

    • Example:

      for i in range(3):
          print(i) # Output: 0 1 2
      

      range(start, stop, step): start defaults to 0, step defaults to 1.

4. Binary Data Types

Used for handling raw binary data, typically in file I/O, network communication, or low-level data manipulation.

  • bytes (Immutable): An immutable sequence of bytes (integers in the range 0 to 255). Represented with a b prefix.

    • Example:

      binary_data = b"example"
      print(binary_data[0]) # Output: 101 (ASCII value of 'e')
      
  • bytearray (Mutable): A mutable version of bytes.

    • Example:

      buffer = bytearray(b"data")
      buffer[0] = 68  # ASCII value for 'D'
      print(buffer)   # Output: bytearray(b'Data')
      
  • memoryview: Provides efficient access and manipulation of binary data from other binary types without needing to copy the data.

    • Example:

      arr = bytearray(b"ABC")
      view = memoryview(arr)
      print(view[0]) # Output: 65 (ASCII value of 'A')
      

5. Mapping Data Type

  • dict (Dictionary): An unordered collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type. Dictionaries are defined using curly braces {} with key-value pairs separated by colons.

    • Example:

      profile = {
          "username": "user123",
          "active": True,
          "role": "admin"
      }
      print(profile["role"]) # Output: admin
      
      # Add a new key-value pair
      profile["last_login"] = "2025-05-21"
      

6. Set Data Types

Sets are unordered collections of unique, immutable elements. They are useful for membership testing, removing duplicates, and mathematical set operations (union, intersection, difference).

  • set: A mutable, unordered collection of unique elements. Defined using curly braces {} or the set() constructor.

    • Example:

      my_set = {2025, "Data", 4.5, 7+2j, 3.14E-3}
      print(my_set) # Order may vary
      
      # Sets only accept immutable elements
      # my_set.add([1, 2]) # This would raise a TypeError
      

      You can add or remove elements from a set.

  • frozenset: An immutable version of a set. Once created, its elements cannot be changed.

7. Boolean Data Type

  • bool: Represents one of two values: True or False.

    • Example:

      is_valid = False
      print(is_valid)       # Output: False
      print(type(is_valid)) # Output: <class 'bool'>
      
      x = 3
      y = 5
      print(bool(x > y))    # Output: False
      

8. None Type

  • NoneType: Represents the absence of a value or a null value. It has only one possible value: None.

    • Example:

      x = None
      print("x = ", x)        # Output: x =  None
      print("type of x = ", type(x)) # Output: type of x =  <class 'NoneType'>
      

Getting and Setting Data Types

Getting Data Type

The built-in type() function can be used to determine the data type of any value or variable.

print(type(456))     # Output: <class 'int'>
print(type(7.89))    # Output: <class 'float'>

x = 12
y = 5.67
z = "World"
p = (40, 50, 60)
q = [70, 80, 90]

print(type(x))       # Output: <class 'int'>
print(type(y))       # Output: <class 'float'>
print(type(z))       # Output: <class 'str'>
print(type(p))       # Output: <class 'tuple'>
print(type(q))       # Output: <class 'list'>

Setting Data Type (Dynamic Typing)

In Python, you don't explicitly declare a variable's type. The type is automatically assigned based on the value you assign.

x = 25
print("x = ", x)         # Output: x =  25
print("type of x = ", type(x)) # Output: type of x =  <class 'int'>

x = "Python is fun!"
print("x = ", x)         # Output: x =  Python is fun!
print("type of x = ", type(x)) # Output: type of x =  <class 'str'>

Primitive vs. Non-primitive Data Types

This is a conceptual distinction:

  1. Primitive Types: Fundamental, built-in types that directly represent simple data values.

    • Integers (int)

    • Floats (float)

    • Booleans (bool)

    • Strings (str)

    • NoneType

  2. Non-primitive Types: Also known as reference types or composite types, these store collections of primitive or other non-primitive types.

    • Lists (list)

    • Tuples (tuple)

    • Dictionaries (dict)

    • Sets (set, frozenset)

    • Bytes and Bytearrays (bytes, bytearray)

Python Data Type Conversion (Type Casting)

Python allows you to convert data from one type to another using built-in constructor functions.

  • int(): Converts to integer.

  • float(): Converts to floating-point number.

  • str(): Converts to string.

  • list(), tuple(), set(): Convert iterable objects to respective sequence or set types.

Example:

## Conversion to integer
a = int(5)       # a will be 5
b = int(7.8)     # b will be 7 (truncates decimal)
c = int("9")     # c will be 9
print(f"int(5)={a}, int(7.8)={b}, int('9')={c}")

## Conversion to float
a = float(6)       # a will be 6.0
b = float(3.3)     # b will be 3.3
c = float("7.77")  # c will be 7.77
print(f"float(6)={a}, float(3.3)={b}, float('7.77')={c}")

## Conversion to string
a = str(8)         # a will be "8"
b = str(4.56)      # b will be "4.56"
c = str("9.99")    # c will be "9.99" (already a string, no change)
print(f"str(8)='{a}', str(4.56)='{b}', str('9.99')='{c}'")

Output:

int(5)=5, int(7.8)=7, int('9')=9
float(6)=6.0, float(3.3)=3.3, float('7.77')=7.77
str(8)='8', str(4.56)='4.56', str('9.99')='9.99'

Quick Revision Table

| Category | Data Types | | :------------ | :----------------------------- | | Text | str | | Numeric | int, float, complex, bool | | Sequence | list, tuple, range | | Binary | bytes, bytearray, memoryview | | Mapping | dict | | Set | set, frozenset | | Special | NoneType |

Summary of Key Data Types

Numeric Types: int, float, complex, bool

Python’s numeric types store numbers. int for whole numbers, float for decimals, complex for numbers with imaginary parts, and bool for True/False.

Text Type: str

Stores sequences of characters enclosed in quotes. Strings are immutable.

Sequence Types: list, tuple, range

Ordered collections. list is mutable, tuple is immutable, and range represents a sequence of numbers efficiently.

Binary Types: bytes, bytearray, memoryview

Handle raw binary data. bytes is immutable, bytearray is mutable, and memoryview offers efficient access.

Mapping Type: dict

Stores key-value pairs. Keys must be unique and immutable.

Set Types: set, frozenset

Unordered collections of unique, immutable elements. set is mutable, frozenset is immutable.

Boolean Type: bool

Represents True or False.

None Type: NoneType

Represents the absence of a value.

SEO Keywords

Python data types tutorial, Built-in data types in Python, Python numeric types explained, String and sequence types in Python, Python list vs tuple, Binary data types in Python, Python dictionary example, Set and frozenset in Python, Python boolean and NoneType, Data type conversion in Python.

Common Interview Questions on Python Data Types

  • What are the different data types in Python?

  • Explain the difference between mutable and immutable data types in Python. Give examples.

  • How is Python dynamically typed? Provide examples.

  • What is the difference between list, tuple, and range in Python?

  • What are binary data types in Python and when are they typically used?

  • How does a dictionary work in Python? Can dictionary keys be mutable types?

  • What is the difference between set and frozenset?

  • What is the purpose and use of the NoneType in Python?

  • How can you convert data between different types in Python?

  • Explain how bool is a subtype of int in Python, with an example.