Understanding Python Data Types
An overview of data types in Python, including scalar, sequence, mapping, and set types.
Data types are essential in programming as they classify or categorize data items. Here's a look at Python's built-in data types:
Scalar Types
- int: Positive or negative whole numbers (without a fractional part), e.g., -10, 10, 456, 4654654.
- float: Real numbers with a floating-point representation, including fractional components, e.g., 1.23, 3.4556789e2.
- complex: Numbers with real and imaginary components, represented as
x + 2y. - bool: Boolean values
TrueorFalse(note the capitalization). - None: Represents the null object, often returned by functions that don't explicitly return a value.
Sequence Types
Sequences are ordered collections of data. Python offers several built-in sequence types:
- String: A collection of characters enclosed in quotes, either single, double, or triple.
- List: An ordered collection of data items, potentially of varying types, enclosed in square brackets.
- Tuple: Similar to lists, but enclosed in parentheses and immutable.
Mapping Type
- Dictionary: An unordered set of key:value pairs, enclosed in curly brackets, e.g.,
{1:"Steve", 2:"Bill"}.
Set Types
- set: A mutable, unordered collection of distinct hashable items, supporting operations like union and intersection.
- frozenset: An immutable version of a set, with elements drawn from other iterables.
Mutable and Immutable Types
Data objects are stored in a computer's memory. Some can be modified during processing (mutable), while others cannot be altered once created (immutable).
- Immutable: Numbers, Strings, and Tuples cannot change their content after creation.
- Mutable: Lists and Dictionaries can be modified — items can be added, deleted, or rearranged.