Python Basics: Data Types
Data types are fundamental to any programming language, and Python is no exception. They define the kind of values a variable can hold and the operations that can be performed on those values. Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable; Python infers it based on the value assigned.
Here's a breakdown of the most common data types in Python:
1. Numeric Types
These represent numerical values.
int(Integers): Whole numbers, positive or negative, without decimals.x = 10 y = -5 print(type(x)) # Output: <class 'int'>float(Floating-Point Numbers): Numbers with decimal points.pi = 3.14159 temperature = 98.6 print(type(pi)) # Output: <class 'float'>complex(Complex Numbers): Numbers with a real and imaginary part. Represented asa + bj, whereais the real part andbis the imaginary part.z = 2 + 3j print(type(z)) # Output: <class 'complex'> print(z.real) # Output: 2.0 print(z.imag) # Output: 3.0
2. Text Type
str(String): A sequence of characters enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...'''or"""..."""). Triple quotes are often used for multi-line strings.name = "Alice" message = 'Hello, world!' long_text = """This is a multi-line string.""" print(type(name)) # Output: <class 'str'>
3. Boolean Type
bool(Boolean): Represents truth values:TrueorFalse. Boolean values are often the result of comparisons.is_valid = True is_empty = False print(type(is_valid)) # Output: <class 'bool'>
4. Sequence Types
These represent ordered collections of items.
list(List): An ordered, mutable (changeable) collection of items. Items are enclosed in square brackets[...].my_list = [1, 2, "apple", 3.14] print(type(my_list)) # Output: <class 'list'> my_list[0] = 10 # Lists are mutable print(my_list) # Output: [10, 2, 'apple', 3.14]tuple(Tuple): An ordered, immutable (unchangeable) collection of items. Items are enclosed in parentheses(...).my_tuple = (1, 2, "banana", 2.71) print(type(my_tuple)) # Output: <class 'tuple'> # my_tuple[0] = 10 # This would raise a TypeError because tuples are immutablerange(Range): Represents a sequence of numbers. Often used in loops.numbers = range(5) # Generates numbers from 0 to 4 print(type(numbers)) # Output: <class 'range'> for i in numbers: print(i)
5. Mapping Type
dict(Dictionary): An unordered collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples). Values can be of any data type. Enclosed in curly braces{...}.my_dict = {"name": "Bob", "age": 30, "city": "New York"} print(type(my_dict)) # Output: <class 'dict'> print(my_dict["name"]) # Output: Bob
6. Set Types
set(Set): An unordered collection of unique items. Enclosed in curly braces{...}. Sets are useful for removing duplicates.my_set = {1, 2, 2, 3, 4, 4, 5} # Duplicates are automatically removed print(type(my_set)) # Output: <class 'set'> print(my_set) # Output: {1, 2, 3, 4, 5}frozenset(Frozen Set): An immutable version of a set.my_frozenset = frozenset([1, 2, 3]) print(type(my_frozenset)) # Output: <class 'frozenset'>
7. None Type
NoneType(None): Represents the absence of a value. It's a special constant in Python.x = None print(type(x)) # Output: <class 'NoneType'>
Type Conversion
You can convert between data types using built-in functions:
int(): Converts to integer.float(): Converts to floating-point number.str(): Converts to string.bool(): Converts to boolean.list(): Converts to list.tuple(): Converts to tuple.set(): Converts to set.dict(): Converts to dictionary.
num_str = "123"
num_int = int(num_str) # Convert string to integer
print(type(num_int)) # Output: <class 'int'>
num_float = 3.14
num_str2 = str(num_float) # Convert float to string
print(type(num_str2)) # Output: <class 'str'>
Understanding data types is crucial for writing correct and efficient Python code. Choosing the right data type for your data can significantly impact performance and readability. The type() function is your friend for checking the data type of a variable.