π Python Data Types β From Basics to Pro (Step-by-Step)
Here's Python data types covered in a crisp, step-by-step beginner-to-pro tutorial. This article addresses all the fundamental types, how they are treated by Python, and practical examples you can experiment with.
Written By: Nivesh Bansal Linkedin, GitHub, Instagram
π What are Data Types?
Each value in Python has a data type. It informs Python about the type of value stored in a variable β a number, string, list, etc.
You don't have to explicitly define data types. Python infers them for you!
x = 5 # int
y = 3.14 # float
name = "Nivesh" # str
π Built-in Data Types in Python
Python supports various built-in data types:
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
|
π’ Numeric Types
int
- Whole numbers
age = 25
float
- Decimal numbers
pi = 3.1415
complex
- Complex numbers (used in advanced math)
z = 3 + 2j
π Text Type: str
Used for strings (text):
greeting = "Hello, world!"
π Boolean Type: bool
Represents True or False:
is_active = True
is_logged_in = False
π Sequence Types
list
- Ordered, mutable collection
colors = ["red", "blue", "green"]
tuple
- Ordered, immutable collection
coordinates = (10, 20)
range
- Sequence of numbers
nums = range(1, 6) # 1 to 5
π Mapping Type: dict
A collection of key-value pairs:
person = {
"name": "Radha",
"age": 22
}
β¨ Set Types
set
- Unique, unordered elements
unique_nums = {1, 2, 3, 2}
frozenset
- Immutable set
frozen = frozenset(["a", "b"])
π« Type Checking
Use type()
to determine a variable's type:
x = 5
print(type(x)) # <class 'int'>
βοΈ Type Conversion
Convert from one type to another using built-in functions:
x = 10
print(float(x)) # 10.0
-
int("5")
β 5 -
str(10)
β "10" -
list("abc")
β ["a", "b", "c"]
π Bonus Tip: Duck Typing
Python has duck typing: βIf it walks like a duck and quacks like a duck, itβs a duck.β
You only need to care about the type when it matters.
π Keep learning, and happy coding!
Written By: Nivesh Bansal Linkedin, GitHub, Instagram
Top comments (2)
Very helpful!
thanks man!!