Reputation: 15934
Currently I have a list with some non-repeating positive integers in it say a = [1,2,6,15,19]
What is the most idiomatic way to create a function that returns a new list that is the result of taking the modulo %x
of each element of a
without having any repeated elements in the output?
Specifically I want f(a,x)
to return [1%x,2%x,6%x,15%x,19%x]
without the repeated elements.
For example f([1,2,6,15,19],4)
would return [1,2,3]
Upvotes: 2
Views: 5005
Reputation: 1122392
Use a list comprehension, and a set()
to filter out duplicates and preserve order:
def f(values, x):
seen = set()
add = seen.add
return [res for res in (i % x for i in values) if res not in seen and not add(res)]
Demo:
>>> f([1,2,6,15,19], 4)
[1, 2, 3]
If order does not need to be preserved, just use a set comprehension instead and return the resulting set:
def f(values, x):
return {i % x for i in values}
Upvotes: 6
Reputation: 43255
To return the list of the set you need a set comprehension wrapped in a list.
def f(l, x):
return list({i % x for i in l})
As per question comments, returning the set may be the best option.
def f(l, x):
return {i % x for in l}
Upvotes: 4