🐍 Python Q2 / 100

What are Python data types?

AI-Powered Answer ✓ Answered

In Python, data types are classifications that specify which type of value a variable has and what type of mathematical, relational, or logical operations can be applied to it without causing an error. Python is dynamically typed, meaning you don't declare the type of a variable when you create it.

What are Data Types?

Data types represent the kind of value stored in a variable. They determine the operations that can be performed on the data and the way it is stored in memory. Python provides several built-in data types to handle various kinds of data efficiently.

Common Python Data Types

Numeric Types

These types represent numerical values. Python supports integers, floating-point numbers, and complex numbers.

  • int: Integers (e.g., 10, -500)
  • float: Floating-point numbers (e.g., 3.14, -0.001)
  • complex: Complex numbers (e.g., 1 + 2j)

Sequence Types

Sequences are ordered collections of items. They allow you to store multiple values in an organized way.

  • str: Strings (e.g., "hello", 'Python')
  • list: Ordered, mutable collection (e.g., [1, 2, 3], ['a', 'b'])
  • tuple: Ordered, immutable collection (e.g., (1, 2, 3), ('x', 'y'))

Set Types

Sets are unordered collections of unique items. They are useful for mathematical set operations.

  • set: Unordered, mutable collection of unique items (e.g., {1, 2, 3})
  • frozenset: Unordered, immutable collection of unique items

Mapping Type

Mappings store data in key-value pairs, where each key maps to a specific value.

  • dict: Unordered, mutable collection of key-value pairs (e.g., {'name': 'Alice', 'age': 30})

Boolean Type

Booleans represent truth values, often used in conditional statements.

  • bool: Represents either True or False

None Type

The None type signifies the absence of a value or a null value.

  • NoneType: Represents the None object, indicating no value

You can check the type of any variable using the type() function:

python
x = 10
y = 3.14
z = "hello"
my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}

print(type(x))      # <class 'int'>
print(type(y))      # <class 'float'>
print(type(z))      # <class 'str'>
print(type(my_list)) # <class 'list'>
print(type(my_dict)) # <class 'dict'>
print(type(True))   # <class 'bool'>
print(type(None))   # <class 'NoneType'>

Mutability and Immutability

Python data types can also be classified as mutable or immutable. Mutable objects can be changed after they are created, while immutable objects cannot. When an immutable object is 'modified', a new object is actually created.

CategoryMutable TypesImmutable Types
Numericint, float, complex, bool
Sequenceliststr, tuple
Setsetfrozenset
Mappingdict
OtherNoneType