Rosamunda
Rosamunda

Reputation: 14980

How to print elements in a list in a plain one-row way?

I have to define a procedure, union, that takes as inputs two lists. It should modify the first input list to be the set union of the two lists. I assume the first list is a set, that is, it contains no repeated elements.

I´ve tried this, and it works:

def union(a, b):
    a.append(b)
    for item in b:
        if item in a:
            a.remove(item)

When I try to test it, this is the output:

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

The output that I should receive is for the excercise: [1,2,3,4,6]

The output that I receive is: [1, 3, [2, 4, 6]]

How may I print the output in order to match the desired one? Or is it the same thing?

Upvotes: 1

Views: 134

Answers (3)

Kristiono Setyadi
Kristiono Setyadi

Reputation: 5643

Try this simple way:

def union(a, b):
    return list(set(a + b))

Upvotes: 0

Akavall
Akavall

Reputation: 86168

a = [1,2,3]
b = [2,4,6]

def union(a, b):
    set_a = set(a)
    for ele in b:
        if ele not in set_a:
            a.append(ele)
    return a

Result:

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

Note that when you use remove, the first element in the list is removed:

>>> a = [1,2,3,2,4,6]
>>> a.remove(2)
>>> a
[1, 3, 2, 4, 6]

Therefore, to get your desired outcome we must keep a as it is, and add to it elements from b that are not it a.

Upvotes: 0

roman
roman

Reputation: 117345

why don't you use a set?

def union(a, b):
    return list(set(a + b))

this will not modify you list BUT set is not ordered, so you can't rely on order of you elements.

if you try to find an error in your code, you could modify it like this:

def union(a, b):
    for item in b:
        if item in a:
            a.remove(item)
    a.extend(b)

if you really want to add new items to a, you can use this:

def union(a, b):
    a.extend([x for x in b if x not in a])

Upvotes: 1

Related Questions