1

I'm trying to create a function with two inputs that can append a value into a list of choice. I'm starting of with two lists to get the code working before I build up.

a = []
b = []

def func(z,x):
   if z == a:
       a.append(x)
   elif z == b:
       b.append(x)
   print(a,b)

For some reason it appends to the first list, then the second, no matter which I select. I've only just started to learn python, so I may have missed something basic.

Matt7425
  • 41
  • 5

1 Answers1

1

== when comparing two lists sees if they contain the same items. An empty list is equivalent to another empty list, so the first time that function is called, it will always append to a. What you could use instead is is (if z is a:), but a much better way is to ignore a and b, and just use z directly:

def func(z, x):
    z.append(x)
    print(a, b)

which brings up doubts as to why this function is needed...

zondo
  • 19,901
  • 8
  • 44
  • 83
  • Thank you, "is" worked. What I wanted is to type a or b into the function first to select which list to append to, then x is the value you want to append. It's a project solely for myself, so it doesn't need to be that intuitive. – Matt7425 May 14 '18 at 20:39
  • 1
    @Matt7425: Yes, but it really doesn't make sense to do that. The point of `is` is to make sure that both variables are the same object. If they are the same object, that means that either name can be used. Since that is true regardless of if it's `a` or `b`, you might as well just use `z` in all cases, which removes the need for any `if` statement. I had a typo in my original answer, but the updated function should work just fine. – zondo May 14 '18 at 20:42
  • Oh, I get what you're saying now, yeah that simplifies things a lot. – Matt7425 May 14 '18 at 20:56