Ad space (banner)
🐍Python Lessons
Lesson 28 / 69

Working with Sets

This lesson covers using Python's set type, so you can manage data without duplicates and search it quickly. It's written for anyone searching "Python set tutorial" or "Python remove duplicates from list".

A set is a "container that won't allow the same value twice." It's handy when you want to remove duplicates from a list, or quickly check whether a value is present. Checking membership with in on a set is also faster than on a list once you have a lot of data — a real performance benefit.

The sample code creates unique_nums from a list containing duplicates, nums, using set(nums), then sorts and displays it with sorted(). Sets have no inherent order, so if you need a predictable output order, you'll need this kind of conversion back to a list, followed by sorting.

A common beginner mistake is trying to access a set's contents by index, which raises an error. You can't write something like unique_nums[0] — to retrieve values, you either loop over it with for, or convert it to a list first. Think of a set primarily as a data structure for quickly checking "is this in here or not."

Sets are also used constantly in real work for deduplication — removing duplicate tags selected in a form, tracking which page IDs have already been visited to avoid double-counting, and more. Anywhere you need duplicate management or fast existence checks, sets are the tool of choice.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)