Python Dynamic Typing: Key Differences from Static Typing

Learn about Python's dynamic typing, which sets it apart from statically typed languages like C/C++ and Java. Understand how, unlike statically typed languages where variable types must be declared and are enforced at compile time, Python allows variables to change types at runtime, providing greater flexibility.



Python - Dynamic Typing

Python is known for being a dynamically typed language, unlike statically typed languages like C/C++ and Java. Let's understand the difference.

Static Typing

In statically typed languages, each variable and its data type must be declared before assigning a value. Assigning a value of a different type will cause a compile-time error.

Example: Static Typing in Java

public class MyClass {
   public static void main(String args[]) {
      int var;
      var = "Hello";
      
      System.out.println("Value of var = " + var);
   }
}
        
Output

/MyClass.java:4: error: incompatible types: String cannot be converted to int
   var = "Hello";
       ^
1 error
        

Why Python is Called Dynamically Typed?

In Python, a variable is just a label or reference to an object in memory, not a named memory location. This means the type of a variable is determined by the type of the object it references, not by a declaration.

Let's see how Python handles variable types dynamically:

Example: Dynamic Typing in Python

var = "Hello"
print("id of var is", id(var))
print("type of var is", type(var))

var = 25.50
print("id of var is", id(var))
print("type of var is", type(var))

var = (10, 20, 30)
print("id of var is", id(var))
print("type of var is", type(var))
        
Output

id of var is 2822590451184
type of var is <class 'str'>

id of var is 2822589562256
type of var is <class 'float'>

id of var is 2822592028992
type of var is <class 'tuple'>
        

We can see that the type of var changes each time it refers to a new object. This flexibility is why Python is called a dynamically typed language.

Dynamic typing makes Python flexible compared to C/C++ and Java. However, it can lead to runtime errors, so programmers need to be cautious.