Python Data Types
Data types in Python define what type of values a variable can hold. They will specify how the data should be stored, accessed, and manipulated in a program. Python has many pre-built data types, but all of them can broadly be categorized based on their purposes and behaviors:
1. Numeric types
a) int (Integer)
- Represents whole numbers (either positive or negative) that don’t have a decimal point.
- Unlimited precision.
- Examples:
x = 10 # Positive integer
y = -200 # Negative integer
b) float (Floating Point)
- Reprents real numbers, but with a decimal point
- Examples:
pi = 3.14159
e = -2.71
c) complex (Complex Numbers)
- Represents numbers as
a + bj
where botha
(real part) andb
(imaginary part) are floats. - Examples:
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
2. Sequence Types
a) str (String)
- Used to store text data.
- Enclosed in single
' '
, double" "
, or triple quotes''' '''
/"" ""
. - Immutable.
- Examples:
name = "Python"
multiline = '''This is
a multiline string.'''
b) list
- Ordered, mutable collection of items.
- It can hold mixed data types.
- Examples:
fruits = ["apple", "banana", "cherry"]
mixed = [1, "Python", 3.14, True]
c) tuple
- Ordered, unmodifiable collection of objects.
- Useful for static data.
- Examples:
coordinates = (10, 20)
person = ("John", 30)
d) range
- Represents an immutable sequence of numbers.
- Often used in loops.
- Examples:
r = range(5) # 0, 1, 2, 3, 4
r2 = range(2, 10, 2) # 2, 4, 6, 8
3. Mapping Type
dict (Dictionary)
- An unordered, mutable collection of key-value pairs.
- Keys must be unique and immutable (strings, numbers, or tuples).
- Examples:
student = {"name": "Alice", "age": 25, "grade": "A"}
4. Set Types
a) set
- An unordered collection of unique elements.
- It is mutable.
- Examples:
numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
b) frozenset
- Immutable version of
set
. - Examples:
frozen = frozenset([1, 2, 3, 4])
5. Boolean Type
bool
- Represents one of two values:
True
orFalse
. - Internally,
True
is1
andFalse
is0
. - Examples:
is_active = True
is_admin = False
6. Binary Types
a) bytes
- Immutable sequence of bytes.
- Examples:
b = b"hello"
b) bytearray
- Mutable sequence of bytes.
- Examples:
ba = bytearray(b"hello")
c) memoryview
- Allows you to access the memory of another binary object without copying.
- Examples:
mv = memoryview(b"hello")
7. None Type
NoneType
- It is represented as the absence of any value or a null value.
- Used as the default return value of those functions which explicitly return nothing.
- Example:
x = None
How to Check the Data Type of a Variable
Use the type()
function:
x = 10
print(type(x)) # <class 'int'>
Type Conversion
Python can convert between data types:
- Implicit Conversion: Automatic conversion (e.g.,
int
tofloat
). - Explicit Conversion: Use type functions like
int()
,float()
,str()
, etc.
num = 10
num_str = str(num) # Converts integer to string