Understanding Python Data Types: A Beginner’s Guide
Python is a powerful, flexible, and beginner-friendly programming language. One of the core features that makes Python so approachable is its use ofdata types. Understanding how Python handles different types of data is essential for writing clean, efficient, and bug-free code.
In this post, we’ll explore the most important built-in data types in Python and how they are used in real-world code.
What Are Data Types?
Adata typedefines the kind of value a variable can hold. For example, numbers, text, and lists are all different types of data. Python isdynamically typed, which means you don’t need to declare a variable’s type explicitly — Python figures it out for you.
age = 30 # intprice = 99.99 # floatname = "Alice" # str
Core Built-in Data Types
Python has several built-in data types. Let’s go over the most commonly used ones:
1.Integers (int
)
Whole numbers, positive or negative, without decimals.
x = 42
2.Floating Point Numbers (float
)
Numbers with a decimal point.
pi = 3.14159
3.Strings (str
)
Sequences of characters, used for text.
message = "Hello, World!"
4.Booleans (bool
)
Logical values:True
orFalse
.
is_active = True
5.Lists (list
)
Ordered, changeable (mutable) collections of items.
colors = ["red", "green", "blue"]colors.append("yellow")
6.Tuples (tuple
)
Ordered, unchangeable (immutable) collections.
coordinates = (10.0, 20.0)
7.Dictionaries (dict
)
Unordered collections of key-value pairs.
person = {"name": "Alice", "age": 30}
8.Sets (set
)
Unordered collections of unique items.
unique_numbers = {1, 2, 3, 3, 2} # {1, 2, 3}
Mutable vs Immutable Types
A key concept in Python is whether a data type ismutable(can be changed) orimmutable(cannot be changed).
Type | Mutable? |
---|---|
int | No |
float | No |
str | No |
tuple | No |
list | Yes |
dict | Yes |
set | Yes |
Type Conversion (Casting)
You can convert between types using built-in functions:
x = "123"y = int(x) # y is now 123 (int)
Checking a Variable’s Type
You can check what type a variable is using thetype()
function:
type("hello") # <class 'str'>type(42) # <class 'int'>