1

I have a sorted list of values i need to filter such that the only values returned are not the same as the value to its left.

For example mylist=[1,2,2,3,3,3,3,6,7,9,9,11] would return [1,2,3,6,7,9,11].

I've done this task using for and if loops but wondering if there is not a more elegant solution using list comprehensions.

Thanks!

0

3 Answers 3

3

I don't think there's a way to do it with list comprehension, but a better way to do it would be:

mylist=[1,2,2,3,3,3,3,6,7,9,9,11]
uniqueList = list(set(mylist))
Sign up to request clarification or add additional context in comments.

Comments

1

In a sorted list, that is by definition the same thing as list(set(mylist)), which just uniquifies your list.

But, code golfing a bit, since you asked for a list-comp, there's the charming:

seen = set()

[x for x in mylist if x not in seen and not seen.add(x)]
Out[3]: [1, 2, 3, 6, 7, 9, 11]

Or:

from itertools import zip_longest

[tup[0] for tup in zip_longest(mylist,mylist[1:]) if len(set(tup)) == 2]
Out[11]: [1, 2, 3, 6, 7, 9, 11]

The latter of which works with your requirement on non-sorted lists as well.

As you can see, both of these are less readable than list(set(mylist)), which should be preferred if you know that your input lists will always be sorted.

3 Comments

Thanks @roippi. Can you explain the mechanics behind solution 1 a bit? Having a little trouble understanding how the "and not seen.add(x)" is filtering the list.
@user2957824 that's the code golf-ish part. set.add does not return anything, so that part is equivalent to and not None which is always true. It also adds x to the set, so the second time around x in seen is True and it gets filtered out.
The value of this answer for me is in showing the basic syntax of a list-comprehension.
1

You can try something like this:

>>> m=set( mylist)
>>> m
set([1, 2, 3, 6, 7, 9, 11])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.