Search code examples
pythonuniquepython-3.4

Generate unique list from a list of lists


I'm trying to define a function that will accept an arbitrary number of lists and will generate a single list of unique elements from those lists. (I'm using Python 3.4)

Example:

a = ['lion', 'tiger', 'panther']
b = ['dog', 'lion', 'bear']
c = ['rat', 'dog', 'tiger']

def merge(*var_list):
    newlist = []
    for item in var_list:
        newlist.append(item)
    return newlist

Evaluating:

merge(a,b)

Produces:

[['lion', 'tiger', 'panther'], ['dog', 'lion', 'bear']]

Ideally, I would like it to generate a list that looks like this:

['lion, 'tiger', 'panther', 'dog', 'bear']  #order is not important

How can I achieve the above result?


Solution

  • You can use set:

    list(set(a+b))
    

    As Greg explain in comments, Python treat each list as a set, where a set has the property of being composed of unordered unique elements.

    By adding sets together, you will be able to keep the property of unordered-ness.

    From the interpreter:

    >>> a+b
    ['lion', 'tiger', 'panther', 'dog', 'lion', 'bear']
    >>> list(set(a+b))
    ['tiger', 'lion', 'dog', 'bear', 'panther']