Python 101 · Data Types and Behaviors

Jan 2, 2016 | Tech Software

Index
Index

Data Types

  • All data types in Python are objects and are passed by object reference.
  • Variables are essentially labels for objects; "modifying" immutable types actually makes a label point to a new address.
Type Name Mutability Behavior
Integer int Immutable Modification: creates new object, similar to Value Copy effect
Float float Immutable Modification: same as above
String str Immutable Modification: same as above
Boolean bool Immutable Modification: same as above, bool inherits from int
Tuple tuple Immutable
  • Modification: cannot be modified in place
  • Empty instance: tuple() or ()
List list Mutable
  • Modification: in-place modification, affects all references
  • Empty instance: list() or []
Dictionary dict Mutable
  • Modification: same as above
  • Empty instance: dict() or {}
Set set Mutable
  • Modification: same as above
  • Empty instance: set()
Custom Class class Mutable by default
  • Modification: in-place attribute modification
  • Empty instance: Foo(bar, ...), constructor dependent

Common Container Methods

  • tuple

    : immutable, ordered, allows duplicate items.
  • list

    : mutable, ordered, allows duplicate items.
  • dict

    : mutable, unordered, forbids duplicate keys.
  • set

    : mutable, unordered, forbids duplicate items.

Common String Methods

  • join, split, find, replace, count;
  • upper, lower, title, capitalize, etc.

Indexing and Slicing

  • works for sequence types such as strings, lists, tuples, etc

F-String

  • preferred over str.format() since Python 3.6

Object Reference & "Labels" to New Addresses

Functions "Modifying" Immutable Inputs

Immutable Custom Classes

Duck Typing

  • A programming concept where an object's suitability is determined by the presence of certain methods and properties, rather than its actual type or inheritance.
  • "If it walks like a duck and quacks like a duck, then it must be a duck." — James Whitcomb Riley

Type Casting, Hints, Checks

  • Implicit by Design

    : Python follows the Duck Typing principle and performs implicit type inference and conversions, but sometimes it can be helpful to explicity suggest or specify types.
  • Typecasting

    : The explicit process of converting a value from one data type to another, which triggers immediate validation and raises an error if the conversion is logically impossible.
  • Type Hints

    : A formal annotation system used to specify the expected data types of variables, function parameters, and return values to improve code clarity and enable static analysis without affecting runtime behavior.
  • Type Checks (Manual, Automated)

    : The process of verifying that a program adheres to type constraints, which can occur statically (before execution) via IDE or dynamically (at runtime) via logic or modules, such as isinstance(), @typechecked, pydantic, or numpy with type specifiers, to ensure data integrity.