Lesson 20 of 34

Sets: Unique Values Only

7 min 25 XP

A set never holds the same value twice. set() is the easiest way to remove duplicates from a list.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Compare two sets: | (union) is everything, & (intersection) is what both share, and - (difference) is what only the first has.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Sets have no order, so set[0] doesn't work. Use sorted() when you need them in order.

Challenge

+25 XP

nums = [5, 3, 5, 1, 3, 9, 1]. Print how many unique numbers there are, then print them as a sorted list on the next line.

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.