How do you get unique values from a python list of objects?

Use a set comprehension. Sets are unordered collections of unique elements, means any duplicates will be removed.

Example:

Suppose class Order has product_id, qty, amount attributes. To get collection of unique product_id:

orders = [ ... ]
products = { order.product_id for order in orders}

If you want to transform a list into collection of unique elements, use set method.

a = ['a', 'b', 'c', 'd', 'b']
b = set(a)
print(b)

Output:

{'b', 'c', 'd', 'a'}

Leave a Reply

Your email address will not be published. Required fields are marked *