Python123
Python123

Reputation: 71

Python removing equal lists

I have some equal lists in my list a:

a = [[a],[a],[b],[b],[c],[c]]

How can I remove the equal lists so that I have the following:

a = [[a],[b],[c]]

I've tried to do it with a set but it doesn't work:

my_set = set()
for elem in a:
    my_set.add(elem)
for x in my_set:
    print(x)

Upvotes: 3

Views: 125

Answers (6)

Midhun C Nair
Midhun C Nair

Reputation: 136

You can use list comprehension instead.

d = [it for i, it in enumerate(a) if it not in a[0:i]]
print(d)

Upvotes: 0

AGN Gazer
AGN Gazer

Reputation: 8378

A variation of @DYZ answer that works with lists containing identical elements regardless of the order:

[x for x,_ in itertools.groupby(map(set, a))]

For example:

>>> a = [['a'],['a'],['b'],['b'],['c', 'a'],['a', 'c']]
>>> [list(x) for x,_ in itertools.groupby(map(set, a))]
[['a'], ['b'], ['a', 'c']]

If ['c', 'a'] and ['a', 'c'] are not considered equal (see comments below by @DYZ) then you can do something like this using set():

map(list, set(map(tuple, a)))

Upvotes: 0

AGN Gazer
AGN Gazer

Reputation: 8378

If ['c', 'a'] and ['a', 'c'] are not considered equal then you can do something like this using set():

map(list, set(map(tuple, a)))

Upvotes: 0

DYZ
DYZ

Reputation: 57033

If you do not mind using itertools:

[x for x,_ in itertools.groupby(sorted(a))]
#[['a'], ['b'], ['c']]

If you do, convert the lists to tuples, create a set of them, and then convert back to lists:

list(map(list, set(map(tuple, a))))
#[['b'], ['c'], ['a']]

Upvotes: 2

Mr_U4913
Mr_U4913

Reputation: 1344

numpy is one of the options

import numpy as np
a = [['a'],['a'],['b'],['b'],['c'],['c']] 
np.unique(a).tolist() #  ['a', 'b', 'c']

Upvotes: 3

aquil.abdullah
aquil.abdullah

Reputation: 3157

You can try this:

a = [['a'],['a'],['b'],['b'],['c'],['c']]
b = list()
for item in a:
    if item not in b:
        b.append(item)

Upvotes: 5

Related Questions