AndrewBird
AndrewBird

Reputation: 5

How to get the list append right with if-elif?

The following code ---

lu,area = ([],)*2
row = [10,20]
column = [1,2]

for x in row:
  for y in column:
            if y==1:
                lu.append(y)
                print(lu)
                print(area)
                
            elif y==2:
                area.append(y)
                print(lu)
                print(area)

is printing ---

[1]
[1]
[1, 2]
[1, 2]
[1, 2, 1]
[1, 2, 1]
[1, 2, 1, 2]
[1, 2, 1, 2]

But, the desired outcome is ---

[1]
[]
[1]
[2]
[1, 1]
[2]
[1, 1]
[2, 2]

Why are both lists being appended together inspite of the if-elif logic?

Thanks for taking the time out to help.

Upvotes: 0

Views: 519

Answers (2)

Abhishek Singhal
Abhishek Singhal

Reputation: 58

There is a problem with the first line where you wrote lu,area = ([],)*2
When you use the * operator in such a way, python creates multiple copies that reference the same object. Thus when you change its value using either variable, it makes changes to the same object.

As stated in Blckknght's answer you can do
lu,area = [], []

One easy way to check for such problems is to use the is keyword. If you type lu is area it returns true which means they are the same object. But after doing lu, area = [],[] you get false as return value which indicates they are different objects.

Upvotes: 0

Blckknght
Blckknght

Reputation: 104762

Your very first line, lu,area = ([],)*2, is too cute for its own good. It's equivalent to lu = area = [], both variables refer to the same (initially empty) list object. When you later start appending to the list, it doesn't matter which variable name you use for it, all the values end up together.

What you probably want is lu, area = [], [], which binds the variables to separate empty lists. You might even want to do the assignments on separate lines, to keep things extra clear:

lu = []
area = []

Upvotes: 1

Related Questions