Beginner’s Guide to Python Variable Initialization

目次

1. Introduction

Python is a programming language known for its simple and readable syntax, and it is used by a wide range of people from beginners to professionals. Among its topics, “variable initialization” is one of the key concepts that beginners encounter first when learning Python. A variable is a “named container” for temporarily storing data within a program. Initialization refers to the act of assigning an initial value to this container. In Python, unlike C or Java, you don’t need to explicitly specify a type, but failing to initialize properly can cause errors or reduce code readability and maintainability. For example, issues such as “I thought I initialized a list as empty, but the value got shared across functions” or “I initialized with None, but the intent wasn’t clear and it led to bugs” are often caused by a lack of understanding of initialization. In this article, we will systematically explain how to initialize variables in Python. We will cover everything from basic numeric and string initialization to complex data types like lists and dictionaries, as well as important considerations for initialization in functions and classes, all presented in a clear and beginner‑friendly manner. If you arrived here by searching for “Python variable initialization,” this article is packed with practical information useful for both work and study, so please read through to the end.

2. What is variable initialization in Python?

What is variable initialization?

Variable initialization means assigning an initial value to a variable before using it in a program. In other words, it’s the first step of telling the program, “I will use this variable for this purpose.” For example, the following code initializes the variable count with the integer 0.
count = 0
Doing this allows calculations and comparisons using the variable count to proceed smoothly.

Characteristics of initialization in Python

Python is called a “dynamically typed language,” so you don’t need to explicitly specify a type when declaring a variable. For example, whether it’s an integer or a string, you can write it as follows and use it immediately.
number = 100        # initialize with an integer
text = "Hello"      # initialize with a string
In C or Java, you need to explicitly specify the type before declaring and initializing a variable, but Python eliminates this hassle, allowing you to write code more intuitively. However, this flexibility can backfire, leading to unexpected data types being assigned or accidentally using an uninitialized variable, which results in errors.

What happens when you use an uninitialized variable?

In Python, attempting to access an uninitialized variable raises a NameError. Below is an example.
print(user_name)
As shown above, accessing user_name before assigning a value results in the following error.
NameError: name 'user_name' is not defined
To avoid such errors, it’s important to always initialize variables before using them.

Implicit initialization vs. explicit initialization

In Python, the common practice is “implicit initialization,” where assigning a value when you need it completes the initialization. However, for safer and clearer code, there are cases where it’s recommended to perform an “explicit initialization” in advance using None or an empty list, for example. For example:
data = None  # value not yet set, but indicates it will be used later
By declaring the existence of a variable in advance, it becomes easier for team development and future code reviews to understand.
年収訴求

3. Basic Initialization Methods and Examples by Data Type

In Python, variable initialization is very simple; it’s done just by assigning a value. Here we introduce the initialization methods for commonly used basic data types along with concrete code examples.

3.1 Initialization of Numbers and Strings

To initialize numbers (integers and floating-point) or strings in Python, you simply assign them as shown below.
count = 0               # integer initialization
temperature = 36.5      # floating-point initialization
message = "Hello"    # string initialization
These initializations rarely cause errors and are intuitive to work with. Numbers and strings are the most fundamental elements in Python, so you should become comfortable handling them smoothly.

3.2 Initialization Using None

When a value hasn’t been decided yet, or you want to explicitly indicate “emptiness,” None is handy.
username = None
By initializing like this, you can indicate in the code that “this variable will receive some value later, but it is currently undefined.” None is similar to the concept of null and can be returned when a function has no return value, among other cases. It is often used together with conditional branching.
if username is None:
    print("Username is not set")

3.3 Initialization of Lists, Dictionaries, Sets, etc.

When handling multiple values, you use lists, dictionaries, or sets. Initialize them as follows.
my_list = []               # empty list
my_dict = {}               # empty dictionary
my_set = set()             # empty set (note: {} creates a dictionary, so be careful)
Each has different uses, so choose the appropriate one for the situation.
  • List (list): an ordered collection of items
  • Dictionary (dict): a data structure composed of key‑value pairs
  • Set (set): used when you want to store data without duplicates
For example, use a list to store a list of usernames, a dictionary for a mapping of user IDs to names, and a set to record IDs that have already been processed.

3.4 Tuple Initialization

A tuple is an “immutable” collection of data that cannot be changed once created. Example initializations are shown below.
empty_tuple = ()                  # empty tuple
point = (10, 20)                  # fixed pair like coordinates
Because immutability is guaranteed, tuples are handy when you want to treat multiple values as a “fixed set.” Note that a single‑element tuple requires a trailing comma, e.g., (value,).
single = (5,)  # this becomes a single-element tuple

Summary: Proper Initialization According to Use Case

Performing appropriate initialization for each data type helps avoid errors and improves code readability. In particular, complex data structures such as lists and dictionaries have nuances when combined with functions and classes discussed later, so it’s important to have a solid understanding at the foundational stage.

4. Common Pitfalls and Mistakes

Initializing variables in Python may look simple, but there are several points where beginners often stumble. Here we explain the “initialization pitfalls” that are easy to overlook and can lead to real bugs or unexpected behavior.

4.1 Beware of Mutable Default Arguments

When defining a function in Python, using lists or dictionaries as default arguments can cause unintended behavior. The code below looks fine at first glance.
def add_item, items=[]):
    items.append(item)
    return items
However, calling this function multiple times results in the previous result being carried over.
print(add_item("A"))  # ['A']
print(add_item("B"))  # ['A', 'B']  # unintended behavior
This issue occurs because items=[] is evaluated only once at function definition time and then reused.
Correct Approach
In such cases, it is safe to use None for initialization and create the list inside the function.
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

4.2 Variable Scope and Initialization Confusion

In Python, global and local variables with the same name are treated as distinct entities depending on scope. In the example below, it appears that the same counter is being used, but because the scopes differ, they refer to separate variables.
counter = 10

def increment():
    counter = counter + 1  # causes error
    print(counter)
This code raises an UnboundLocalError at runtime because assigning to counter inside the function makes Python treat it as a “local variable.” Since that local variable has not been initialized, an error occurs.
To Make It Work Correctly
  • Use the global keyword if you need to modify the variable inside the function
  • Or design the code to pass values via arguments and return values
def increment():
    global counter
    counter += 1
    print(counter)

4.3 Pitfalls of Initialization Without Type Awareness

Because Python is dynamically typed, the type of a variable can change automatically. This flexibility is convenient but can also lead to bugs.
value = 5       # integer
value = "5"     # now a string
Such code may appear to work, but later treating value as a number will raise an error.
result = value + 1  # TypeError: can only concatenate str (not "int") to str
Countermeasures
  • If you want to fix the type, use type annotations (see below)
  • At a minimum, be clear about what each variable is intended to hold when you initialize it

Brief Summary: Knowing the Pitfalls Helps Prevent Bugs

While Python is a beginner-friendly language, there are hidden traps behind its “readability.” In particular, handling mutable objects, scope differences, and type ambiguity are common sources of bugs even at a professional level. To avoid such trouble, it’s important to understand not only the basics of initialization but also the common mistakes and how to address them in advance.
侍エンジニア塾

5. Best Practices for Initialization in Functions and Classes

Variable Initialization in Functions

Initializing Local Variables

Variables defined inside a Python function are treated as local variables of that function. They are independent of the outside scope, and attempting to use a variable that hasn’t been initialized within the function will result in an error.
def greet():
    message = "Hello"
    print(message)

greet()
Thus, it is important to always initialize variables within the function before using them.

Using Safe Default Arguments

As mentioned in the previous chapter, using mutable objects (lists or dictionaries) as default arguments can lead to unintended sharing of values. A recommended pattern for safe initialization is to use None and initialize inside the function.
def append_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items
This style promotes higher reusability and leads to safe, predictable function design.

Variable Initialization in Classes (__init__ Method)

In Python classes, the __init__ method is called when an instance is created. This is where instance variables are initialized.

Initializing Instance Variables

class User:
    def __init__(self, name):
        self.name = name
        self.age = None  # Variables intended to be assigned later are also initialized here

user1 = User("Sato")
print(user1.name)  # → Sato
In this way, by initializing with self., each instance can hold its own unique data.

Be Careful with the Difference Between Class Variables

Python has instance variables and class variables. Using them without understanding the difference can lead to unintended data sharing.
class Sample:
    shared_list = []  # Class variable (shared across all instances)

    def __init__(self):
        self.my_list = []  # Instance variable (independent for each instance)

a = Sample()
b = Sample()

a.shared_list.append("A")
b.shared_list.append("B")

print(a.shared_list)  # → ['A', 'B']
print(b.shared_list)  # → ['A', 'B']
Class variables are shared across all instances, making them unsuitable for storing state. When you need independent data per state, always use self. and initialize it in __init__.

Clarify Code Intent Through Initialization

Variable initialization in functions and classes is an important design element that makes clear “how this variable is intended to be used.” Proper initialization makes the code easier to understand for future readers (or your future self).

6. Initialization Using Type Hints (Optional, Union)

What Are Type Hints?

Type hints are a mechanism that explicitly indicates that a variable or a function’s parameters and return values are intended to use a certain type. They have been standard-supported since Python 3.5, and you can benefit from code completion and warnings provided by static analysis tools (such as mypy or Pyright) and editors (like VS Code, PyCharm, etc.).
name: str = "Yamada"
age: int = 25
is_active: bool = True
As shown above, you can explicitly specify a type by writing a colon (:) and the type name after the variable name.

Initialization Using Optional

Optional is a type hint that indicates a variable may be either a certain type or None. For example, for a variable that hasn’t been set yet but may later hold a string, you would use it as follows.
from typing import Optional

username: Optional[str] = None
This has the same meaning as the following:
from typing import Union

username: Union[str, None] = None
In other words, Optional[X] is shorthand for Union[X, None]. Writing it this way makes it clear that “this variable may be in an unset state (None), but it is ultimately expected to become a str.”

Allowing Multiple Types with Union

Using Union enables a flexible definition where “this variable can take any one of several types.”
from typing import Union

data: Union[int, str] = 42
data = "text"  # both are OK
This is used to retain the benefits of dynamic typing while restricting the type options and preventing unexpected errors.

Initializing Lists and Dictionaries with Type Hints

Lists and dictionaries can also be precisely specified with type hints.
from typing import List, Dict

names: List[str] = []
user_ages: Dict[str, int] = {}
Writing it as shown above clearly conveys specifications such as “this list contains only strings” and “this dictionary has string keys and integer values.”

Benefits and Advantages of Using Type Hints

  • Editor autocomplete is enhanced: narrowed suggestions reduce typos
  • Helps catch bugs early: mismatches can be detected in advance with tools like mypy
  • Serves as documentation: makes it easier to understand how code works, even for others
Especially when beginners step up to intermediate level, the habit of “being aware of types” is extremely important.

Summary: Clear Initialization for Readable, Safe Code

Python is a language that isn’t strict about types, but leveraging type hints significantly improves code reliability. By clearly indicating intent with Optional or Union during initialization, you can more easily prevent bugs and make future maintenance easier.

7. Frequently Asked Questions (FAQ)

Here we compile common beginner questions related to “Python variable initialization” in a Q&A format. Each answer includes practical code examples and cautions.

Q1. Do I have to specify a type for variables in Python?

A1. It works without type annotations, but using type hints makes it safer. Because Python is dynamically typed, you can use variables simply by writing:
age = 25        # No type annotation (int)
name = "Sato"   # No type annotation (str)
However, assigning a different type later can lead to unexpected bugs. Therefore, to improve code readability, autocomplete support, and type checking, using type hints is recommended.
age: int = 25

Q2. Why initialize a variable with None?

A2. To explicitly indicate that a value does not exist yet. In Python, using None clearly shows that a value has not been set yet.
result = None  # Assuming a value will be assigned later

Q3. What is the correct way to initialize a list?

A3. An empty list can be initialized with [], but be careful with function arguments.
items = []  # Normal initialization is fine
However, using [] as a default argument can cause the value to be shared.
def add(item, items=[]):  # ❌ Values accumulate across calls
    items.append(item)
    return items
The correct approach is to use None and initialize inside the function.
def add(item, items=None):  # ✅
    if items is None:
        items = []
    items.append(item)
    return items

Q4. Why did a class variable share its value with other instances?

A4. You need to understand the difference between class variables and instance variables. Python classes have two kinds of variables:
  • Class variable: shared across the entire class
  • Instance variable: each instance has its own independent value
class Sample:
    shared_list = []  # Class variable (shared across all instances)

    def __init__(self):
        self.my_list = []  # Instance variable (independent per instance)

a = Sample()
b = Sample()

a.shared_list.append("A")
b.shared_list.append("B")

print(a.shared_list)  # → ['A', 'B']
print(b.shared_list)  # → ['A', 'B']
To avoid unintended sharing, use an instance variable like self.variable_name and initialize it inside __init__.

Q5. How do you choose between 0, "", and None for a variable’s initial value?

A5. Choose based on whether the value is “undetermined” or definitively “empty”.
StateExample initial valueMeaning
Unset / undeterminedNoneValue has not been decided yet
Confirmed empty0, "", []Clearly known to be “empty”
For example, use None when waiting for user input, and use [] when an empty list is already the intended default. Clarifying the intent improves the safety and readability of subsequent processing.

8. Summary | Best Practices for Python Initialization

In this article, we have covered a wide range of topics on “Python variable initialization,” from basics to practical applications, common mistakes, and how to use type hints. Python is a dynamically typed, flexible language, but that also means that “the ambiguity of initialization” can easily cause unexpected errors and bugs. That’s why mastering the following best practices for initialization directly leads to healthy coding.

✅ Summary of Initialization Best Practices

  • Explicitly initialize basic types (int, str, list, etc.)
  count = 0
  name = ""
  items = []
  • Use None when you want to indicate an undefined state
  result = None
  • Do not use mutable types (list, dict, etc.) as default arguments in functions
  def func(data=None):
      if data is None:
          data = []
  • In classes, initialize each instance with self.variable_name
  class User:
      def __init__(self, name):
          self.name = name
  • Use type hints (Optional, Union) to clarify the intent of the code
  from typing import Optional
  age: Optional[int] = None

✍️ Advice for Beginners

In Python, having code that “works” is different from having code that is “safe and clear.” It’s fine to prioritize getting things to work at first, but as you gradually learn explicit initialization and proper use of types, you’ll be able to write code with fewer bugs and higher reliability.

📘 Related Topics (for stepping up)

  • Understanding Python’s scope and namespaces
  • mypy and other automated type checking
  • Simplifying initialization with data classes (@dataclass)
  • Leveraging type completion via IDEs (VS Code, PyCharm)
Thank you for reading to the end. I hope this article helps those struggling with “Python variable initialization” to resolve their questions and level up.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール