2.2 Python Core Data Types (BT101CO)
In Python, every value has a data type. Since everything in Python is an object, data types are actually classes and variables are instances (objects) of these classes. Understanding these core types is essential for effective programming.
1. Numeric Types
These represent numbers and are the most basic building blocks for mathematical problem-solving.
- Integer (
int): Represents whole numbers (positive, negative, or zero) without a decimal point.
Example:10,-5,1002. - Floating Point (
float): Represents real numbers with a decimal point.
Example:10.5,3.14,-0.001. - Complex (
complex): Used for scientific calculations, represented as $a + bj$, where $a$ is the real part and $b$ is the imaginary part.
Example:3 + 4j.
2. Sequence Types
Sequences are ordered collections of items. A critical concept here is the difference between mutable (changeable) and immutable (unchangeable) sequences.
- String (
str): An immutable sequence of characters enclosed in single (' '), double (" "), or triple (''' ''') quotes. - List (
list): A mutable ordered collection of items (can be of different types). Defined using square brackets[].
Example:[1, "Ashok", 3.4]. - Tuple (
tuple): An immutable ordered collection. Once created, its elements cannot be changed. Defined using parentheses().
Example:(1, 2, 3).
3. Mapping Type (Dictionary)
Dictionary (dict): An unordered collection of key-value pairs. Each key must be unique and is used to retrieve its corresponding value. Defined using curly braces {}.
Example: {"Name": "Ashok", "RollNo": 101}.
4. Set Types
Set (set): An unordered collection of unique items. Sets are used to eliminate duplicate values and perform mathematical set operations like union and intersection.
Example: {1, 2, 3, 3} becomes {1, 2, 3}.
5. Boolean Type
Boolean (bool): Represents one of two values: True or False. These are essential for control flow (if-statements and loops). Note that in Python, True is internally treated as 1 and False as 0.
6. None Type
None: A special data type that represents the absence of a value or a null value. It is often used to initialize variables that will be assigned a value later.
Summary: Mutability vs. Immutability
Understanding mutability is crucial as it affects how memory is managed and how data is passed between functions:
| Data Type | Category | Mutable? |
|---|---|---|
| int, float, complex | Numeric | No |
| str | Sequence | No |
| tuple | Sequence | No |
| list | Sequence | Yes |
| dict | Mapping | Yes |
| set | Set | Yes |