Python Data Types
Data Types
In programming, a data type defines two things about a value:
- What kind of value it is — text, a whole number, a decimal number, a collection of items, a true/false value, and so on.
- What operations can be performed on it — for example, numbers can be divided, strings can be converted to uppercase, and lists can have items appended to them.
Understanding data types helps you predict how your code will behave. For example, 5 + 5 gives 10, but "5" + "5" gives "55", because the second expression works with strings, not numbers.
Python Is Dynamically Typed
Python is a dynamically typed language. You do not need to declare a variable's data type — Python determines it automatically from the value you assign.
x = 10 # Python decides x is an int
x = "hello" # now x refers to a str
The type belongs to the value, not to the variable name. A variable is simply a name that refers to a value, and it can refer to a value of any type.
Different data types serve different purposes, such as storing text, numbers, collections, or logical values.
Built-in Data Types in Python
Python provides several built-in data types, grouped into the following categories:
| Category | Data Types | What They Store |
|---|---|---|
| Text Type | str | Text (sequences of characters) |
| Numeric Types | int, float, complex | Whole numbers, decimal numbers, complex numbers |
| Sequence Types | list, tuple, range | Ordered collections of items |
| Mapping Type | dict | Key–value pairs |
| Set Types | set, frozenset | Unordered collections of unique items |
| Boolean Type | bool | True or False |
| Binary Types | bytes, bytearray, memoryview | Raw binary data |
| None Type | NoneType | The special value None, meaning "no value" |
A Quick Look at Each Type
| Type | Example Value | Mutable? | Notes |
|---|---|---|---|
str | "Python" | No | Text in single or double quotes |
int | 42 | No | Whole numbers of any size |
float | 3.14 | No | Numbers with a decimal point |
complex | 2 + 3j | No | Real and imaginary parts; used in scientific computing |
list | ["pen", "book"] | Yes | Ordered, changeable, allows duplicates |
tuple | (10, 20) | No | Ordered, unchangeable |
range | range(1, 5) | No | A sequence of numbers, often used in loops |
dict | {"name": "Asha"} | Yes | Stores data as key–value pairs |
set | {"red", "green"} | Yes | Unordered, no duplicates |
frozenset | frozenset({"red"}) | No | An unchangeable set |
bool | True | No | Logical values |
bytes | b"Data" | No | Immutable sequence of bytes |
bytearray | bytearray(8) | Yes | Mutable sequence of bytes |
memoryview | memoryview(b"abc") | — | Accesses the memory of another binary object without copying |
NoneType | None | No | Represents the absence of a value |
What Does "Mutable" Mean?
A mutable value can be changed after it is created. An immutable value cannot.
items = ["pen", "book"]
items.append("eraser") # Lists are mutable: the same list is changed
print(items)
name = "python"
upper_name = name.upper() # Strings are immutable: a NEW string is created
print(name)
print(upper_name)
Expected output:
['pen', 'book', 'eraser']
python
PYTHON
- The list was modified in place, so
itemsnow contains three values. - The string method
upper()did not changename; it returned a new string.
This difference matters when values are shared between variables or passed to functions. Each data type has its own dedicated lesson later in this course.
Checking the Data Type
You can identify the data type of any variable or value using the built-in type() function.
Example
value = 42
print(type(value))
Expected output:
<class 'int'>
The output means that value refers to an object of the int class. In Python, every data type is a class, and every value is an object of some class.
type() helps you understand how Python is interpreting your data — for example, to confirm whether a value from user input is a string or a number.
Checking a Type With isinstance()
To check whether a value is of a particular type, use isinstance(). It returns True or False:
price = 49.75
print(isinstance(price, float))
print(isinstance(price, str))
Expected output:
True
False
isinstance() is preferred over comparing type() results in real programs, because it also works correctly with subclasses.
Data Types Are Assigned Automatically
In Python, the data type is determined at the moment a value is stored in a variable.
Examples
text = "Python Basics" # str
number = 100 # int
price = 49.75 # float
imaginary = 2 + 3j # complex
items = ["pen", "book", "eraser"] # list
coordinates = (10, 20) # tuple
numbers = range(1, 5) # range
profile = {"username": "admin", "active": True} # dict
colors = {"red", "green", "blue"} # set
fixed_colors = frozenset({"red", "green", "blue"}) # frozenset
is_valid = False # bool
raw_data = b"Data" # bytes
buffer = bytearray(8) # bytearray
view = memoryview(bytes(4)) # memoryview
empty_value = None # NoneType
Each variable automatically gets the data type that matches its assigned value. Notice how the syntax of the value tells Python which type to create:
- Quotes →
str - A whole number →
int - A decimal point →
float - A
jsuffix →complex - Square brackets
[ ]→list - Parentheses
( )→tuple - Curly braces with
key: valuepairs →dict - Curly braces with single values →
set TrueorFalse→bool- A
bprefix before quotes →bytes None→NoneType
You can confirm any of these with type():
print(type(coordinates))
print(type(profile))
print(type(empty_value))
Expected output:
<class 'tuple'>
<class 'dict'>
<class 'NoneType'>
A Common Trap: Empty Curly Braces
empty = {}
print(type(empty))
Expected output:
<class 'dict'>
{} creates an empty dictionary, not an empty set. To create an empty set, use set().
Explicitly Setting a Data Type
If you want to control the data type or convert a value from one type to another, Python provides a constructor function for each type. The function has the same name as the type.
Examples
a = str(2025)
b = int("30")
c = float("19.99")
d = complex(4, 5)
e = list(("cat", "dog", "bird"))
f = tuple((1, 2, 3))
g = range(10)
h = dict(city="Chennai", code=600001)
i = set(("HTML", "CSS", "Python"))
j = frozenset(("HTML", "CSS", "Python"))
k = bool(0)
l = bytes(6)
m = bytearray(6)
n = memoryview(bytes(6))
What Each Constructor Produces
| Variable | Code | Resulting Value | Type |
|---|---|---|---|
a | str(2025) | '2025' | str |
b | int("30") | 30 | int |
c | float("19.99") | 19.99 | float |
d | complex(4, 5) | (4+5j) | complex |
e | list(("cat", "dog", "bird")) | ['cat', 'dog', 'bird'] | list |
f | tuple((1, 2, 3)) | (1, 2, 3) | tuple |
g | range(10) | range(0, 10) | range |
h | dict(city="Chennai", code=600001) | {'city': 'Chennai', 'code': 600001} | dict |
i | set(("HTML", "CSS", "Python")) | A set of the three strings (order may vary) | set |
j | frozenset(("HTML", "CSS", "Python")) | An immutable set of the three strings | frozenset |
k | bool(0) | False | bool |
l | bytes(6) | b'\x00\x00\x00\x00\x00\x00' (six zero bytes) | bytes |
m | bytearray(6) | bytearray(b'\x00\x00\x00\x00\x00\x00') | bytearray |
n | memoryview(bytes(6)) | A memory view object | memoryview |
A few points worth noticing:
list(("cat", "dog", "bird"))uses double parentheses: the inner pair creates a tuple, andlist()converts that tuple into a list.bytes(6)andbytearray(6)with an integer create a sequence of that many zero bytes, not the number 6.bool(0)isFalsebecause zero is considered "empty" or "false-like". Any non-zero number isTrue.
Constructor functions are especially useful when working with user input, file data, or data from external systems, where values often arrive as text and must be converted before use.
Practical Example: Converting User Input
age_text = "25" # Imagine this came from input()
age = int(age_text) # Convert to a number
print(age + 1)
print(type(age))
Expected output:
26
<class 'int'>
Without the conversion, age_text + 1 would raise a TypeError, because you cannot add a number to a string.
Common Mistakes
- Treating numeric strings as numbers:
"10" + 5raises aTypeError. Convert first withint("10"). - Using
{}for an empty set:{}is an empty dictionary. Useset(). - Converting invalid text:
int("abc")orint("19.99")raises aValueError. The text must represent a whole number forint(). - Expecting sets to keep order: Sets do not keep items in the order you wrote them.
Related Concepts
- Python Numeric Data Types —
int,float, andcomplexin detail - Python Type Casting — converting between types safely
- Python Strings, Lists, Tuples, Sets, and Dictionaries — each covered in its own lesson
- Python None — the special "no value" object