Tuesday 4 June 2013

Set union of two lists in Python

Hi there!

This is my first blog post so please be patient with me. Today I started a small course about Computer Science and as programming language is using Python. For me this the first time when I use Python and I am impressed by the syntax and other features. I am coming from Java and c# but I hope I will do fine with Python to.

One of my tasks for today it was to define a function in Python that takes as input two lists a and b, it does set union on them and the result is the list a modified with the new values. I find it very easy to do, I didn't had to use any indexes or something like that, just 3 lines of code and problem solved.

Here is the code:

def union(a, b):
    for el in b:             #iterate over list b
        if el not in a:      #if element of b is not in a
            a.append(el)     #append the element to a

Now a test in console it should look like:
a = [1, 2, 4]
b = [2, 3, 6]
union(a, b)
print a
>>> [1, 2, 3, 4, 6]
print b
>>> [2, 3, 6]

That's it.

1 comment:

  1. Wow, Fantastic Blog, it’s so helpful to me, and your blog is very good, I’ve from your blog here, Keep on going, my friend; I will keep an eye on it,learned a lot. And i still waiting for next thought...Bootstrap Themes - Bootstrap 3.0 - 100% Responsive

    ReplyDelete