Question

I have a list of objects of class C. Each object has an attribute attrib. I want to know the number of different values attrib can take in the list.

This works, but it's 4 lines long. Is there a way to make it shorter? Nicer? More efficient?

class C:
    def __init__(self, val):
        self.attrib = val

# my list of objects.
# attrib is either 0, 1 or 2 (so we have 3 different values) for any object in the list
objects = [C(x % 3) for x in xrange(10)] 


# Calculation :
tmpList = [] # temporary list to perform calculation
for o in objects:
    if o.attrib not in tmpList :
        tmpList.append(o.attrib)
print len(tmpList) # print 3
Was it helpful?

Solution

Here is one shorter version:

len(set([x.attrib for x in objects]))

Regarding time complexity, you can improve your original codes from O(n^2) to O(n) by changing tmpList to a Set. Because if o.attrib not in tmpList: is an O(n) operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top