How to get unique values from a python list of objects

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

cars = [...] # A list of Car objects.

models = {car.model for car in cars}

This will iterate over your list cars and add the each car.model value at most once, meaning it will be a unique collection.


If you want to find cars that only appear once:

from collections import Counter
car_list = ["ford","toyota","toyota","honda"]
c = Counter(car_list)
cars = [model for model in c if c[model] == 1 ]
print cars
['honda', 'ford']

Tags:

Python

List