Mutable default arguments don't generally do what you want. Instead, try this:

class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList 
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList 
Answer from Michael J. Barber on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › class init method: best way for default value assignments
r/learnpython on Reddit: class init method: best way for default value assignments
December 18, 2021 -

I am learning linked lists in python using classes.

One place that I am learning from is doing:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

The other place is doing:

class Node:
    def __init__(self, value, next = None):
        self.value = value
        self.next = next

I can't figure out what difference it makes to use either init method. I tried to search this answer out using StackOverflow, but I had no luck.

I get that one is able to define 'next' during instantiation and the other would need to be defined after instantiation, but when would and why would you use one over the other?

edit: Thanks all. I am just starting to understand classes and still overthinking a little.

🌐
GeeksforGeeks
geeksforgeeks.org › python › __init__-in-python
__init__ in Python - GeeksforGeeks
... class Dog: def __init__(self, ... b.breed, b.age) ... When creating Dog("Buddy"), Python uses the defaults, breed = "Mixed", age = 1....
Published: May 11, 2026
🌐
Stack Overflow
stackoverflow.com › questions › 71934568 › python-are-these-default-values-being-passed-to-the-init-function-necessary
Python: Are these default values being passed to the __init__ function necessary? - Stack Overflow
If someone using the class, for whatever reason, does del mypizza.slices, then future access to mypizza.slices will still "work", but will retrieve the value from the class attribute (since the instance attribute was blown away). Sane code should almost never do this. In all other ways, there is no relationship between the class level attributes and the defaults defined for the __init__ initializer method; the moment __init__ assigns to self.slices and self.temperature, it shadows the class level attributes so they cannot be directly accessed from that instance of the class (without deleting the instance attributes or bypassing the instance to look at the values on the class itself).
🌐
Rip Tutorial
riptutorial.com › default values for instance variables
Python Language Tutorial => Default values for instance variables
Similarities in syntax, Differences in meaning: Python vs. JavaScript ... If the variable contains a value of an immutable type (e.g. a string) then it is okay to assign a default value like this · class Rectangle(object): def __init__(self, width, height, color='blue'): self.width = width self.height = height self.color = color def area(self): return self.width * self.height # Create some instances of the class default_rectangle = Rectangle(2, 3) print(default_rectangle.color) # blue red_rectangle = Rectangle(2, 3, 'red') print(red_rectangle.color) # red
Top answer
1 of 6
187

Extending bp's answer, I wanted to show you what he meant by immutable types.

First, this is okay:

>>> class TestB():
...     def __init__(self, attr=1):
...         self.attr = attr
...     
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1

However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:

>>> class Test():
...     def __init__(self, attr=[]):
...         self.attr = attr
...     
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>> 

Note that both a and b have a shared attribute. This is often unwanted.

This is the Pythonic way of defining default values for instance variables, when the type is mutable:

>>> class TestC():
...     def __init__(self, attr=None):
...         if attr is None:
...             attr = []
...         self.attr = attr
...     
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]

The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.

2 of 6
83

The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. Python documentation explains the difference, but here are some examples:

Exhibit A

class Foo:
  def __init__(self):
    self.num = 1

This binds num to the Foo instances. Change to this field is not propagated to other instances.

Thus:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1

Exhibit B

class Bar:
  num = 1

This binds num to the Bar class. Changes are propagated!

>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3

Actual answer

If I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?

The code in exhibit B is plain wrong for this: why would you want to bind a class attribute (default value on instance creation) to the single instance?

The code in exhibit A is okay.

If you want to give defaults for instance variables in your constructor I would however do this:

class Foo:
  def __init__(self, num = None):
    self.num = num if num is not None else 1

...or even:

class Foo:
  DEFAULT_NUM = 1
  def __init__(self, num = None):
    self.num = num if num is not None else DEFAULT_NUM

...or even: (preferrable, but if and only if you are dealing with immutable types!)

class Foo:
  def __init__(self, num = 1):
    self.num = num

This way you can do:

foo1 = Foo(4)
foo2 = Foo() #use default
🌐
Python Examples
pythonexamples.org › python-default-values-for-properties-in-class
Set Default Values for Properties in Class in Python
As we already mentioned, we can use named parameters in __init__() function definition to set default value for the properties.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › dataclasses.html
dataclasses — Data Classes
Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory. init: If true (the default), this field is included as a parameter to the generated __init__() method.
🌐
Anvil
anvil.works › anvil q&a
Understand the behavior of default params in python classes - Anvil Q&A - Anvil Community Forum
September 30, 2021 - What I’m trying to do: Understand the behavior of default params in python classes. I made a sort of random change to the class init, which achieves the behavior I want, but I don’t understand why it does. What I’ve tried and what’s not working: Originally in the Week Custom component the init looked like: def __init__(self, week_number, days = [], **properties): self.days = days self.week_number = week_number self.init_components(**properties) When printing the length of the ...
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python __init__: an overview
Python __init__: An Overview
October 14, 2024 - There are mainly three types of Python __init__ constructors: ... The default __init__ constructor in Python is the constructor that does not accept any parameters, except for the ‘self’ parameter. The ‘self’ is a reference object for that class.
🌐
Mimo
mimo.org › glossary › python › init-function
Python __init__() Function: Syntax, Usage, and Examples
The Python __init__() function is a special method defined within a class. It runs automatically when a class is instantiated, which makes it ideal for setting default values or handling any setup required for new objects.
🌐
AlgoMaster
algomaster.io › home › python › __init__ method
__init__ Method | Python | AlgoMaster. ...
June 6, 2026 - Keeping derived values in sync with their source is its own design question, and the @property decorator is one common answer. For this lesson, the takeaway is just that __init__ sets attributes once, not continuously. If a constructor parameter has a sensible default, you can give it one in the parameter list, and callers who don't care about that parameter can leave it out:
🌐
Abdul Wahab Junaid
awjunaid.com › home › default values for instance variables in python
Default values for instance variables in python | Abdul Wahab Junaid
August 14, 2023 - In this example, the Person class has an __init__ method that takes name and age as arguments, with age having a default value of 18.
🌐
Udacity
udacity.com › blog › 2021 › 11 › __init__-in-python-an-overview.html
__init__ in Python: An Overview | Udacity
June 10, 2026 - Each one would hold different values. They all came from the same class. This is the pattern you will use most often. Required parameters make it clear what data each object needs to work properly. Python’s __init__ supports default parameter values, just like any other function.
🌐
W3Schools
w3schools.com › PYTHON › python_class_init.asp
Python __init__() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... All classes have a built-in method called __init__(), which is always executed when the class is being initiated. The __init__() method is used to assign values to object properties, or to perform operations that are necessary when the object is being created.
🌐
pythontutorials
pythontutorials.net › blog › how-should-i-declare-default-values-for-instance-variables-in-python
How to Declare Default Values for Instance Variables in Python: Class vs __init__ – Which is More Pythonic?
The __init__ method is Python’s constructor: it initializes new instances. Declaring defaults here involves assigning values to self (the instance) inside __init__, often using default arguments.
🌐
Stack Overflow
stackoverflow.com › questions › 41991692 › default-parameter-value-in-this-init-methods-definition
python - Default parameter value in this __init__() method's definition? - Stack Overflow
February 1, 2017 - I am looking at some python code to control a camera and having some trouble understanding it due to being new at python. I see that the src parameter is set to 0. Does this mean that if a src is not given 0 will be used otherwise the given src will be used? class WebcamVideoStream: def __init__(self, src=0): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.VideoCapture(src) ... Yes indeed, that's the concept behind a default parameter.
🌐
Copahost
copahost.com › home › init in python: how object initialisation works
init python: Learn how to use __init__ to initialize objects in ...
August 29, 2023 - Writing Car("Toyota", "Corolla") runs it, and the arguments you pass go to its parameters — all of them except self, which Python supplies. ⚠️ And it isn’t a constructor, strictly speaking. The object already exists by the time __init__ runs; its job is to fill it in. This guide covers self, default values, inheritance with super(), the mutable default trap, and when a dataclass makes __init__ unnecessary.
🌐
Pythontutorial
pythontutorial.org › mastering `__init__` in python
Mastering `__init__` in Python | PythonTutorial.org
Returning a value from __init__. The initializer must return None — the instance is already made, and Demo() will return it regardless. An explicit return of anything else is an error: class Broken: def __init__(self): return self # __init__ must return None Broken() # TypeError: __init__() should return None, not 'Broken' Mutable default arguments.