-2

I have recently started trying to learn Python, and I try to improve the way I write code, and make it more "Pythonic". Therefore, it would really be nice if someone could explain to me if the following can be formulated more elegantly. Hopefully this is not a duplicate (I checked, but you never know)

I have a list of 5 elements, and I want to return specific elements. Let's say for example that I have [1, 2, 3, 3, 4]. I already have a function double(list), that if a list element exists twice returns that element (in this case 3).

I would like to generate from this list a tuple that contains the numbers that are exist only once (1, 2, 4).

One option is the following:

  1. Run the double(list) function and get the value of the element that is double.
  2. Create an empty tuple
  3. Iterate over the list items, and if the value is not equal to what the double(list) function returned, add it to the tuple
  4. Return the tuple.

My question is: is there a more elegant/Pythonic way of doing this? (in one line, using maybe a more complex expression?)

Thanks in advance

eidimon
  • 29
  • 9

3 Answers3

1

The general way to do this is to make a set out of the elements and then count them, or just use collections.Counter, then go through the list and include only the appropriate elements, by either creating an empty list and then adding to it with a traditional loop or by using a comprehension with a filter.

>>> import collections
>>> l = [1, 2, 3, 3, 4]
>>> c = collections.Counter(l)
>>> new_list = [item for item in l if c[item] < 2]
>>> new_list
[1, 2, 4]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

I would use collections.Counter for that:

>>> import collections
>>> l = [1, 2, 3, 3, 4]
>>> c = collections.Counter(l)
>>> [el for el in l if c[el] == 1]
[1, 2, 4]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Since you want a single-line solution (well except for the actual list declaration of course :) ):

your_list = [1, 2, 3, 3, 4]

uniques = [item for item in your_list if your_list.count(item) == 1]
Guillaume
  • 5,497
  • 3
  • 24
  • 42
  • Thanks! This is what I was looking for. Someone also pointed me to a thread where the list is turned into a set first, which should remove duplicates. So now I already have two options :-) – eidimon Sep 16 '16 at 08:21