Python Data Types
In Python, data types are used to classify different types of data that a variable can hold. Python has a rich set of built-in data types, which can be categorized into several main groups:
1. Numeric Types
Python supports three distinct numeric types:
int: Integer numbers, such as10,-5,0.float: Floating-point (decimal) numbers, such as3.14,-0.001.complex: Complex numbers, with real and imaginary parts, such as1 + 2j.
Example:
a = 10 # int
b = 3.14 # float
c = 1 + 2j # complex
You can use standard arithmetic operators (+, -, *, /, etc.) with these types.
2. Text Type
str: Represents a sequence of characters (a string). Strings can be enclosed in single, double, or triple quotes.
Example:
name = "Alice"
greeting = 'Hello, World!'
multiline = """This is a
multi-line string."""
Strings are immutable, meaning their content cannot be changed once they are created. You can concatenate strings using + and repeat them with *.
full_name = "Alice" + " " + "Smith" # Concatenation
print("Hello!" * 3) # Repeats the string 3 times
3. Sequence Types
Python provides several sequence types to store collections of items.
a. List: An ordered, mutable collection of items, which can hold elements of different types.
my_list = [1, "apple", 3.14, True] # A list can have different data types
my_list[0] = 100 # Lists are mutable, so you can modify elements
b. Tuple: An ordered, immutable collection of items. Once created, its elements cannot be changed.
my_tuple = (1, "banana", 3.14)
c. Range: Represents an immutable sequence of numbers, typically used for looping.
my_range = range(1, 10) # Generates numbers from 1 to 9
4. Mapping Type
dict(Dictionary): An unordered collection of key-value pairs, where keys are unique.
Example:
person = {"name": "Alice", "age": 25}
print(person["name"]) # Access value by key
person["age"] = 26 # Modify value
Dictionaries are mutable, so you can add, modify, or remove key-value pairs.
5. Set Types
Sets are unordered collections of unique elements.
a. Set: A mutable collection of unique elements.
my_set = {1, 2, 3, 3, 4} # Duplicate values are ignored
print(my_set) # Output: {1, 2, 3, 4}
b. Frozenset: An immutable version of a set.
my_frozenset = frozenset([1, 2, 3])
6. Boolean Type
bool: RepresentsTrueorFalsevalues, often used in conditional expressions.
Example:
is_active = True
is_complete = False
Boolean values result from comparison operations (==, !=, <, >, etc.) and logical operators (and, or, not).
7. Binary Types
Python provides binary data types for working with binary data (e.g., in file operations, network protocols).
bytes: Immutable sequences of bytes.bytearray: Mutable sequences of bytes.memoryview: Allows access to the internal data of an object without copying it.
Example:
byte_data = b"Hello" # A bytes object
byte_array = bytearray([65, 66, 67]) # A mutable byte array
8. None Type
NoneType: Represents the absence of a value. The special valueNoneis used to indicate that a variable does not have a value or that a function does not return anything.
Example:
x = None
9. Type Checking
You can use the type() function to check the data type of any variable.
x = 5
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
10. Type Casting
You can convert variables from one data type to another using Python’s built-in casting functions.
int(): Convert to an integer.float(): Convert to a float.str(): Convert to a string.list(): Convert to a list.tuple(): Convert to a tuple.set(): Convert to a set.dict(): Convert to a dictionary (from a list of key-value pairs).
Example:
a = 3.14
b = int(a) # b becomes 3
c = "123"
d = int(c) # d becomes 123
e = list("Hello") # Converts string to a list: ['H', 'e', 'l', 'l', 'o']
Example of Data Types in Action:
# Numeric types
x = 10 # int
y = 3.14 # float
# String type
name = "Alice"
# List type
fruits = ["apple", "banana", "cherry"]
# Tuple type
coordinates = (10, 20)
# Dictionary type
person = {"name": "Alice", "age": 25}
# Boolean type
is_active = True
# Set type
unique_numbers = {1, 2, 3, 3}
# None type
result = None
# Type checking
print(type(fruits)) # Output: <class 'list'>
print(type(is_active)) # Output: <class 'bool'>
These are Python’s basic data types. Each one has its own unique characteristics, and together, they allow for flexible and powerful programming.