Python Forum
Extending list doesn't work as expected
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extending list doesn't work as expected
#1
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:

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.
Reply
#2
list1, lst2 are attributes. h is a variable. These are all references to objects, not objects themselves. When you execute "h = list1", you are assigning the variable "h" to reference the object reverenced by "self.list1". Now "h" and "self.list1" reference the same list object. When you execute "h.extend(self.list2)", you modify the object referenced by h, which is also referenced by "self.list1". self.list1 is unchanged, only the list object referenced by self.list1 has changed.

An object and a variable that references an object are two very different things in Python. Understanding this is key to understanding Python.
Reply
#3
I think, outside of the class Test you would need a copy of list1 or list2, or you will alter them, but within the class, this seems to work ok without list1.copy() or list2.copy().

Oh the joys of classes!

class Test:
    def __init__(self):
        self.list1 = [1, 2, 3]
        self.list2 = [5, 6, 7]
 
    def f(self, opt=1):
        if not opt in (1, 2, 3, 4):
            raise ValueError('f() only takes 1, 2 ,3 or 4 as options.')
        if opt == 1:
            h = self.list1
        elif opt == 2:
            h = self.list2
        elif opt == 3:
            h = self.list1 + self.list2
        elif opt == 4:
            h = self.list1 + self.list2
            h.extend(self.list2)
        return h

t = Test()
t.f()
t.f(2)
t.f(3)
t.f(4)
t.f(5)
Of course, you can reassign t.list1 or t.list2 to another list!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't list require global keyword? johnywhy 9 964 Jan-15-2024, 11:47 PM
Last Post: sgrey
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,008 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,438 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 881 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,926 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  How to work with list kafka_trial 8 2,111 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  color code doesn't work harryvl 1 954 Dec-29-2022, 08:59 PM
Last Post: deanhystad
  client.get_all_tickers() Doesn't work gerald 2 1,767 Jun-16-2022, 07:59 AM
Last Post: gerald
  pip doesn't work after Python upgrade Pavel_47 10 4,355 May-30-2022, 03:31 PM
Last Post: bowlofred
  For Loop Works Fine But Append For Pandas Doesn't Work knight2000 2 2,089 Dec-18-2021, 02:38 AM
Last Post: knight2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020