All the list getting appended of a dict if you are updating only first element list of dict

Peter Otten __peter__ at web.de
Wed Nov 15 05:00:50 EST 2017


Radhey Parashar wrote:

> I am facing 1 issue with python related to append command in a list


> class CITY:
> 
>     num = 0
> 
>     connectivity = []

The way you wrote it the connectivity list is shared between all instances 
of the CITY class. Consult a Python tutorial to learn why.

To get per-instance lists you have to write an initializer like the one in 
the following example:

class City:
    def __init__(self, num):
        self.num = num
        self.connectivity = []





More information about the Python-list mailing list