0

I have a small problem with my Python 2 program.

Here is my function:

def union(q,p):
      q = q + p
      q = set(q)
      return q, p

Then I have created new two lists and called my function:

a = [1,2,3]
b = [2,4,6]
union(a,b)

Finally I'm printing out a and b:

>>>print a
[1,2,3]
>>>print b
[2,4,6]

As you can see my function didn't change the value of a. Why? How can I fix that? What am I doing wrong?

NOTE: a used to be [1,2,3,4,6] instead of [1,2,3]

Thanks.

5 Answers 5

3

Assign return values back to a and b:

>>> def union(q,p):
...       q = q + p
...       q = set(q)
...       return q, p
... 
>>> a = [1,2,3]
>>> b = [2,4,6]
>>> a, b = union(a, b)
>>> a
set([1, 2, 3, 4, 6])
>>> b
[2, 4, 6]

To get a list from set, use list as Haidro commented:

>>> list(a)
[1, 2, 3, 4, 6]
Sign up to request clarification or add additional context in comments.

2 Comments

One more question, how can I make a list from set?
@MichaelVayvala Just call list back on it: list(a)
2

Your function doesn't change it in place, it returns the new items. Thus, you have to return the result to a variable:

a, b = union(a, b)

Comments

2

Your function never mutates the object in a. Either mutate it, or assign the value returned from the function back to it.

Comments

0

While the principle is the same, here's another way of achieving it.

>>> def union(a,b):
...     a = set(a) | set(b)
...     return a,b
... 
>>> a = [1,2,4]
>>> b = [5,7,8]
>>> a,b = union(a,b)
>>> a
set([1, 2, 4, 5, 7, 8])
>>> b
[5, 7, 8]
>>> list(a)
[1, 2, 4, 5, 7, 8]

1 Comment

Line 2: TypeError: unsupported operand type(s) for BitOr: 'set' and 'set'
0

As said by other answers, you have to assign what is returned by union. This is because inside union you don't modify q, you create a new local variable (which happens to be called q also).

If you want to modify what is passed as reference you have to:

def union_mod(q, p):
  q.extend(p)
  return set(q), p

Now, what you pass as q is modified (it will continue to be a list, can't change type). So:

In [1]: a = [1,2,3]

In [2]: b = [2,4,6]

In [3]: def union_mod(q, p):
   ...:     q.extend(p)
   ...:     return set(q), p
   ...: 

In [4]: union_mod(a,b)
Out[4]: (set([1, 2, 3, 4, 6]), [2, 4, 6])

In [5]: a
Out[5]: [1, 2, 3, 2, 4, 6]

In [6]: b
Out[6]: [2, 4, 6]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.