nup_logo

Machine Learning with Python

Lecture 2. Python types, mutables and immutables


Alexander Avdiushenko
October 10, 2023

Python Properties:

  • Multiparadigm (object-oriented, functional, ...)
  • "Batteries included" (rich standard library)
  • PEP (Python Enhanced Proposal); What's new in Python 3.12
  • Strict dynamic typing

About Life

  • Python is a universal glue for APIs/libraries/frameworks/distributed systems
  • Comes in handy every day
  • But it's not worth writing projects with serious infrastructure in Python

Data type — a set of values and operations over these values (IEEE Std 1320.2-1998), their representation in memory.

Helps programmers find errors in the code.

Dynamic (duck) typing — "If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck."

duck

Types in Python

Strict (strong) typing — the presence of type consistency safety and memory access safety.

In Python, there is no type casting (almost).

Float

From 1991 to 2018, Guido van Rossum was the "benevolent lifetime dictator" of the Python language.

guido_python

(Im)mutability

String (str)

Python STR algorithmic complexites

  • Inserting a letter to the beginning/middle/end of the string? O(n)
  • Getting the length of a string? O(1)
  • Searching a letter in a string? O(n)
  • Deleting a letter from a string? O(n)
  • Adding a string to another string? (i.e. concatenating) O(m + n)

list

Joy of using typed arrays in Python directly from C

list — mutable data type in Python, so its complexities are

  • Updating an item in the list by index? O(1)
  • Inserting into a list? O(n)
  • Deleting from a list? O(n)
  • Appending to the end of a list? O(1)
  • Concatenating two lists? O(n+m)
  • Getting the length of a list? O(1)
  • Searching in a list? O(n)

tuple

tuple — immutable data type in Python, so

  • Updating an item in a tuple by index? --
  • Inserting into a tuple? --
  • Deleting from a tuple? --
  • Appending to the end of a tuple? --
  • Concatenating two tuples? O(n + m)
  • Getting the length of a tuple? O(1)
  • Searching in a tuple? O(n)

dict — dictionaries (associative arrays)

From the Python method documentation

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

Quine

A computer program that outputs an exact copy of its source code.

Programs that use external data (reading program text from a file, input from the keyboard, etc.) are not considered quines.