What Are Data Types in Python?
In programming, a data type defines what kind of value a variable can hold and how that value can be used. Python automatically determines a variable’s type at runtime, so explicit type declarations are not required. This flexibility makes Python a dynamically typed language.
You can check the type of any value or variable using the built-in type() function.
Built-In Data Types in Python
Python includes several built-in data types. These are categories of objects the language supports natively:
| Category | Data Types |
|---|---|
| Text Type | str |
| Numeric Types | int, float, complex |
| Sequence Types | list, tuple, range |
| Mapping Type | dict |
| Set Types | set, frozenset |
| Boolean Type | bool |
| Binary Types | bytes, bytearray, memoryview |
| None Type | NoneType |
Numeric Data Types
Numeric types represent numbers:
-
int: Whole numbers (e.g.10,-5). -
float: Decimal numbers (e.g.3.14,2.0). -
complex: Numbers with real and imaginary parts (e.g.2 + 3j).
Example:
x = 10
Text Type
-
str: Used for text, created with single ('...') or double ("...") quotes.
Example:
Strings can also be multi-line using triple quotes ("""...""").
Sequence Types
Sequence types allow storing ordered collections:
-
list: Mutable sequence (e.g.[1, 2, 3]). -
tuple: Immutable sequence (e.g.(1, 2, 3)). -
range: Represents a sequence of numbers (e.g.range(5)).
Example:
Mapping Type
-
dict: Stores key-value pairs (e.g.{"name": "Alice", "age": 30}).
Example:
Dictionaries are unordered (prior to Python 3.7) and allow fast lookup by key.
Set Types
-
set: Unordered collection of unique elements. -
frozenset: Immutable version of a set.
Example:
Sets automatically remove duplicates.
Boolean Type
-
bool: Holds one of two values:TrueorFalse. Often used in conditions and loops.
Example:
Booleans are also subclasses of integers (True == 1, False == 0).
Binary Types
Binary types represent raw bytes of data:
-
bytes: Immutable sequence of bytes. -
bytearray: Mutable sequence of bytes. -
memoryview: View of another binary object without copying.
Example:
None Type
-
NoneType: Represents the absence of a value. There is only oneNoneobject in Python.
Example:
This type often acts as a placeholder.
Checking and Converting Types
Use type() to check a data type. You can convert between types using functions like int(), float(), str(), etc.
Example: