Python From Beginner to Advanced

0% completed

Previous
Next
Python - Set Basics

A set in Python is a collection of unique elements that is both unordered and unindexed. Sets are commonly used for removing duplicate values, performing mathematical operations like union, intersection, and difference, and checking membership efficiently.

Unlike lists or tuples, sets:

  • Do not allow duplicate values (only unique elements are stored).
  • Do not maintain order (items may appear in a different order than defined).
  • Do not support indexing or slicing like lists and tuples.

Sets are useful when working with large datasets, mathematical operations, and fast lookups.

Creating a Set

A set in Python can be created using:

  • Curly braces {} – Used to define sets directly.
  • The set() function – Useful when converting lists or other iterables into sets.
Image

Example 1: Defining a Set Using Curly Braces "{}"

Python3
Python3

. . . .

Explanation

  • The set automatically removes duplicate values ('apple' appears twice but is stored only once).
  • The order of elements is not guaranteed when printed.

Example 2: Defining a Set Using "set()" Function

Python3
Python3

. . . .

Explanation

  • The set() function converts a list into a set, automatically removing duplicates.
  • This method is useful when dealing with data containing repeated elements.

Creating an Empty Set

An empty set cannot be created using {} because {} defines an empty dictionary. Instead, you must use the set() function.

Example 3: Creating an Empty Set

Python3
Python3

. . . .

Explanation

  • {} creates an empty dictionary, not a set.
  • set() creates an empty set correctly.

Sets in Python are unordered collections of unique elements and are ideal for removing duplicates and performing mathematical operations.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next