Yandex

Python set() Function – Create a Set from Iterable



Python set() Function

The set() function in Python is used to create a set object. A set is an unordered collection of unique items — meaning it automatically removes duplicates.

Syntax

set([iterable])

Parameters:

  • iterable – (Optional) Any iterable such as list, tuple, string, or dictionary keys.

Returns:

  • A new set object containing unique elements.

Example 1: Convert a List to a Set

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}

Example 2: Create a Set from a String

text = "banana"
letters = set(text)
print(letters)
{'b', 'a', 'n'}

Note: The order may vary because sets are unordered.

Example 3: Empty Set

empty = set()
print(empty)
set()

Warning: Using {} creates an empty dict, not a set.

Use Cases of set()

  • Remove duplicates from a list
  • Check for unique items
  • Perform set operations like union, intersection, difference

Example 4: Removing Duplicates Using set()

data = ["apple", "banana", "apple", "cherry"]
unique_fruits = list(set(data))
print(unique_fruits)
['banana', 'cherry', 'apple']

(Order may vary)

Common Mistakes

  • {} is an empty dictionary, not a set — use set() for an empty set
  • Sets do not support indexing or slicing
  • Items in a set must be hashable (e.g., no lists)

Interview Tip

set() is often used in coding problems involving uniqueness, duplicates, or fast lookups without ordering.

Summary

  • set() converts iterables into a set of unique elements
  • Used to remove duplicates or perform set operations
  • Unordered and unindexed collection
  • Use set(), not {}, to create an empty set

Practice Problem

Write a program to read 5 names from the user and display only the unique names entered.

names = []
for _ in range(5):
    names.append(input("Enter a name: "))
print("Unique names:", set(names))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M