Element That Appear More That Once in the List in Python

element that appear more that once in the list in Python

Convert to a set then back again:

list(set(d))

If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated:

[x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]

Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available:

a = []
for x in d:
if x not in a:
a.append(x)

Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element.

How to remove all elements in a list that appear more than once

The following will work:

list_1 = [1, 2, 3, 4, 4, 3, 3, 7]
res = [i for i in list_1 if list_1.count(i) == 1]

>>>print(res)
[1, 2, 7]

How do I print values only when they appear more than once in a list in python

You could make the following adjustments:

c = Counter(seqList[1:])  # slice to ignore first value, Counter IS a dict already 

# Just output counts > 1
for k, v in c.items():
if v > 1:
print('-value {} appears multiple times ({} times)'.format(k, v))

# output
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)

What would be the python function that returns a list of elements that only appear once in a list

Here is the function that you were looking for. The Iterable and the corresponding import is just to provide type hints and can be removed if you like.

from collections import Counter
from typing import Iterable
d = [1,1,2,3,4,5,5,5,6]

def retainSingles(it: Iterable):
counts = Counter(it)
return [c for c in counts if counts[c] == 1]

print(retainSingles(d))

Output:

[2, 3, 4, 6]

get the values of elements in the list which occurs only twice not more than twice

Here use this:

lst2 = list(set([x for x in lst if lst.count(x)==2]))

use this if you don't want to change the order:

lst = [595, 595, 344, 344, 628, 628, 628, 353, 353, 353, 353, 353]
lst2=[]
[lst2.append(x) for x in lst if lst.count(x)==2 and x not in lst2]
print(lst2)


Related Topics



Leave a reply



Submit