Sets

Behave mostly like lists with the distinction that they can not contain duplicate values.

Example: check wether there are duplicates in a list or not:

With a for loop:

some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

duplicates = []
for value in some_list:
    if some_list.count(value) > 1:
        if value not in duplicates:
            duplicates.append(value)

print(duplicates)
# Output: ['b', 'n']

Withsets:

some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
# Output: set(['b', 'n'])

Other methods

Intersection

You can intersect two sets.

Example:

valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
# Output: set(['red'])

Difference

You can find the invalid values in the above example using the difference method.

Example:

valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.difference(valid))
# Output: set(['brown'])

You can also create sets using the new notation:

a_set = {'red', 'blue', 'green'}
print(type(a_set))
# Output: <type 'set'>

Last updated