L2·Control & Collections

🎯Sets

Unordered collections of unique hashables.

setunionintersection

§ 1Creation

{1,2,3} or set([1,2,3]). Empty set is set(), because {} is a dict.

§ 2Set algebra

a | b union, a & b intersection, a - b difference, a ^ b symmetric difference.

§ 3O(1) membership

x in s is average O(1) for sets and dicts, O(n) for lists.

Example

1a = {1,2,3,4}
2b = {3,4,5,6}
3print(a | b) # {1,2,3,4,5,6}
4print(a & b) # {3,4}
5print(a ^ b) # {1,2,5,6}

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What does {} create?