May-09-2024, 01:36 PM
Adding a list using the += operator or the extend function gives strange results when used in a class (maybe also outslde a class, I didn't check this).
This is an example script to demonstate this:
If another list is added to h by explicitly adding two lists together it does work.
It is also strange that everything works well if I later on select the second list only.
I don't understand what is happening here.
This is an example script to demonstate this:
class Test: def __init__(self): self.list1 = [1, 2, 3] self.list2 = [5, 6, 7] def f(self, opt=1): h = self.list1 if opt == 2: h = self.list2 if opt == 3: h = self.list1 + self.list2 if opt == 4: h.extend(self.list2) return h t = Test() print('Print the first list:', t.f(1)) print('Print the second list:', t.f(2)) print('Two lists added together:', t.f(3)) print('First list again:', t.f(1)) print('Exntending one list with the other:', t.f(4)) print('Should only print the first list:', t.f(1)) print('Printing the second list -- works:', t.f(2))Every call of f(), h is initialised with list1. Somehow this doesn't seem to work if during a previous call of f() h was extended to.
If another list is added to h by explicitly adding two lists together it does work.
It is also strange that everything works well if I later on select the second list only.
I don't understand what is happening here.