-2

I want to create a list with elements appearing only once. Here's what I've tried.


years_of_birth = years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]

ages = []

for year in years_of_birth:
    ages.append(2022 - year)

print(ages)

unique_ages = []

for age in ages:
    if operator.countOf(1, age):
        print(unique_ages)
baduker
  • 19,152
  • 9
  • 33
  • 56
user8083
  • 113
  • 5
  • First search result: [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – 1372 upvotes and 58 answers. – wovano Dec 07 '22 at 14:21
  • Or: [find unique value from python list](https://stackoverflow.com/questions/33171410/find-unique-value-from-python-list) – wovano Dec 07 '22 at 14:22
  • I want to print a new list with only the unique elements of the previous one, is that not obvious from the code itself where i define "unique_ages = []" @wovano – user8083 Dec 07 '22 at 15:30
  • In that case your question is answered here: https://stackoverflow.com/questions/33171410/find-unique-value-from-python-list – wovano Dec 07 '22 at 15:32
  • 1
    Does this answer your question? [find unique value from python list](https://stackoverflow.com/questions/33171410/find-unique-value-from-python-list) – Yevhen Kuzmovych Jan 05 '23 at 13:51

1 Answers1

0

operator.countOf(a, b) is used for counting the number of occurrences of b in a. So if you want a boolean you have to add a comparison like:

if operator.countOf(years_of_birth, 1990) == 1:

But it's easier to just use set since it removes duplicates:

list(set(ages))
Pablo
  • 643
  • 9
  • 12
  • Using `set` is incorrect since it does not only return the unique elements, which is the question. – wovano Dec 07 '22 at 15:34
  • @movano not sure what you mean. Have you tried `print(set([1,2,2,3,1]))` in python? You get `{1,2,3}` – Pablo Feb 07 '23 at 19:47
  • Exactly, you get `{1, 2, 3}`, but 2 is not unique in the list, since it occurs twice. It's not completely clear what the OP wants, but your two methods provide different results. – wovano Feb 08 '23 at 06:32