Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Tuple vs Set: What's the Difference?

Python Tuple vs Set - Complete Comparison

Learn the key differences between Python tuples and sets and when to use each.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Tuples vs Sets – What's the Big Difference?
  • Mutability: The Biggest Difference
  • Uniqueness: Sets Remove Duplicates
  • Ordering: Tuples Keep Order, Sets Don't
  • Performance: Which Is Faster?
  • Memory Usage
  • Available Methods
  • Dictionaries: Tuples Can Be Keys
  • When to Use Each
  • Quick Summary Table
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Mutability — tuples can't change, sets can
  • Uniqueness — tuples allow duplicates, sets don't
  • Ordering — tuples keep order, sets don't
  • Performance — which one is faster for what
  • Memory — which one uses less memory
  • When to use — choosing the right one

Tuples vs Sets – What's the Big Difference?

Tuples and sets are both used to store collections of items, but they're built for very different purposes. They look different, they work differently, and you use them in different situations.

The short answer is: tuples are immutable and ordered, sets are mutable and unordered with no duplicates. But there's a lot more to it than that. Let's break it down.

💡 Here's the thing: The choice between a tuple and a set affects immutability, uniqueness, and performance. Choose wisely!

Mutability: The Biggest Difference

1

Tuples Are Immutable, Sets Are Mutable

This is the most important difference. A tuple cannot be changed after creation. A set can be changed — you can add, remove, or modify elements.

# Tuple — immutable (can't change)
my_tuple = (1, 2, 3, 4, 5)
# my_tuple[0] = 10  # TypeError! Can't change a tuple

# Set — mutable (can change)
my_set = {1, 2, 3, 4, 5}
my_set.add(6)       # Works
my_set.remove(2)    # Works
my_set.add(3)       # No effect (already exists)
print(my_set)       # {1, 3, 4, 5, 6}

# Why this matters:
# Tuples protect your data from accidental changes
# Sets let you modify your data as needed

What this means for you:

  • Tuples — locked, safe from accidental changes
  • Sets — flexible, you can add and remove
  • Tuples are good for data that should never change

Quick Check: What happens if you try to change a tuple? (Answer: TypeError)

Uniqueness: Sets Remove Duplicates

2

Tuples Allow Duplicates, Sets Don't

A tuple can have duplicate values. A set automatically removes duplicates.

# Tuple — can have duplicates
my_tuple = (1, 2, 2, 3, 3, 3, 4)
print(my_tuple)  # (1, 2, 2, 3, 3, 3, 4)
print(len(my_tuple))  # 7

# Set — automatically removes duplicates
my_set = {1, 2, 2, 3, 3, 3, 4}
print(my_set)  # {1, 2, 3, 4}
print(len(my_set))  # 4

# Why this matters:
# Use a tuple when duplicates are okay
# Use a set when you need unique items

Key point:

  • Tuples — allow duplicates
  • Sets — remove duplicates automatically
  • Sets are great for removing duplicates

Quick Check: What happens if you put duplicates in a set? (Answer: They are automatically removed)

Ordering: Tuples Keep Order, Sets Don't

3

Tuples Are Ordered, Sets Are Unordered

Tuples remember the order you put things in. Sets don't — they store items in a way that's optimized for quick lookups.

# Tuple — preserves order
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0])  # apple — index works!
print(my_tuple[1])  # banana
print(my_tuple[2])  # cherry

# Set — no guaranteed order
my_set = {"apple", "banana", "cherry"}
# You can't use indexes!
# print(my_set[0])  # TypeError!

# The order of a set can change
print(my_set)  # {'cherry', 'apple', 'banana'} (order may vary)

# Why this matters:
# Use a tuple when order matters
# Use a set when order doesn't matter

Key point:

  • Tuples — ordered, indexable
  • Sets — unordered, not indexable
  • If order matters, use a tuple

Quick Check: Can you access a set element by index? (Answer: No — sets are unordered)

Performance: Which Is Faster?

4

Sets Are Faster for Membership Testing

Sets are optimized for fast lookups. Checking if something is in a set is much faster than checking in a tuple, especially for large data.

import time

# Create data
big_tuple = tuple(range(1000000))
big_set = set(range(1000000))

# Membership test in tuple
start = time.time()
999999 in big_tuple
tuple_time = time.time() - start

# Membership test in set
start = time.time()
999999 in big_set
set_time = time.time() - start

print(f"Tuple membership: {tuple_time:.6f}s")
print(f"Set membership: {set_time:.6f}s")

# Output example:
# Tuple membership: 0.008000s
# Set membership: 0.000001s

# Sets are much faster for checking if something exists!

Performance summary:

  • Sets — much faster for membership testing
  • Tuples — faster for iteration and ordered access
  • Choose based on what you need

Quick Check: Which is faster for checking if an item exists? (Answer: Set)

Memory Usage

5

Tuples Use Less Memory

Tuples are more memory-efficient than sets because they don't store hash tables. Sets have overhead for storing hash values.

import sys

# Create tuple and set with same data
my_tuple = tuple(range(1000))
my_set = set(range(1000))

print(f"Tuple size: {sys.getsizeof(my_tuple)} bytes")
print(f"Set size: {sys.getsizeof(my_set)} bytes")

# Output example:
# Tuple size: 8,056 bytes
# Set size: 32,984 bytes

# Tuples use much less memory!
# Why? Sets store hash tables for fast lookups.

Memory summary:

  • Tuples — use less memory
  • Sets — use more memory (hash tables)
  • For large datasets, memory matters

Quick Check: Which uses less memory: tuple or set? (Answer: Tuple)

Available Methods

6

What You Can Do With Each

Tuples have very few methods because they can't change. Sets have many methods for adding, removing, and set operations.

# Tuple methods (only two!)
my_tuple = (1, 2, 3)
print(my_tuple.count(2))  # 1 — how many times 2 appears
print(my_tuple.index(3))  # 2 — position of 3

# That's it! No add, no remove, no union.

# Set methods (many!)
my_set = {1, 2, 3}
my_set.add(4)          # Add
my_set.remove(2)       # Remove
my_set.union({4, 5})   # Combine sets
my_set.intersection({3, 4})  # Find common
my_set.difference({4, 5})    # Elements in set but not in another
print(my_set)          # {1, 3, 4}

Key difference:

  • Tuples — count(), index() only
  • Sets — add, remove, union, intersection, difference, and more
  • Choose based on what you need to do

Dictionaries: Tuples Can Be Keys

7

Tuples Can Be Keys, Sets Cannot

Dictionary keys must be immutable. Tuples are immutable, so they work. Sets are mutable, so they don't.

# Tuple as dictionary key — works!
coordinates = {}
coordinates[(10, 20)] = "Point A"
print(coordinates)  # {(10, 20): 'Point A'}

# Set as dictionary key — TypeError!
# coordinates = {}
# coordinates[{10, 20}] = "Point B"  # TypeError: unhashable type: 'set'

# Why this matters:
# This is a common interview question!
# "Can you use a set as a dictionary key?" -> NO
# "Can you use a tuple as a dictionary key?" -> YES

Key point:

  • Dictionary keys must be hashable
  • Tuples are hashable (if they contain hashable items)
  • Sets are not hashable (they are mutable)
  • This is a big reason to use tuples

Quick Check: Can a set be a dictionary key? (Answer: No — sets are mutable)

When to Use Each

8

Which One Should You Choose?

# Use tuples when:
# 1. Data should never change
DAYS_OF_WEEK = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

# 2. You need a dictionary key
coordinates = {(10, 20): "Point A"}

# 3. Order matters
playlist = ("song1", "song2", "song3")

# 4. You need to return multiple values
def get_user():
    return "Alice", 25, "Engineer"  # Returns a tuple

# Use sets when:
# 1. You need unique values
unique_visitors = {"alice", "bob", "charlie"}

# 2. You need fast membership testing
if "alice" in unique_visitors:
    print("Alice visited!")

# 3. You need set operations
set1 = {"python", "java", "c++"}
set2 = {"python", "flask"}
common = set1.intersection(set2)

# 4. Order doesn't matter
tags = {"python", "tutorial", "beginner"}

Simple rule of thumb:

  • Use tuples — when data is fixed, order matters, or you need a dictionary key
  • Use sets — when you need uniqueness, fast lookups, or set operations
  • When in doubt, ask: "Can this data change?"

Quick Summary Table

9
Feature Tuple Set
Mutability Immutable ❌ Mutable ✅
Duplicates Allowed ✅ Not Allowed ❌
Order Preserved ✅ Not Preserved ❌
Index Access ✅ Yes ❌ No
Membership Check Slow (O(n)) Fast (O(1)) ✅
Memory Smaller ✅ Larger
Methods count, index Many (add, remove, union, etc.) ✅
Dictionary Key ✅ Yes ❌ No
Best For Fixed, ordered data Unique data, fast lookups

Common Mistakes

10

Things to Watch Out For

Forgetting the Comma in Single-Element Tuples

# WRONG — this is an integer, not a tuple!
not_a_tuple = (10)
print(type(not_a_tuple))  # <class 'int'>

# CORRECT — comma makes it a tuple
correct_tuple = (10,)
print(type(correct_tuple))  # <class 'tuple'>

Using a Set When Order Matters

# WRONG — sets don't preserve order
my_set = {"apple", "banana", "cherry"}
# print(my_set[0])  # TypeError!

# CORRECT — use a tuple for ordered data
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0])  # apple

Using a Tuple When You Need to Add or Remove

# WRONG — tuples can't change
my_tuple = (1, 2, 3)
# my_tuple.add(4)  # AttributeError

# CORRECT — use a set for mutable data
my_set = {1, 2, 3}
my_set.add(4)  # Works!

Quick Check: What's the most common mistake with tuples? (Answer: Forgetting the comma for single-element tuples)

Try It Yourself

Compare tuples and sets in the editor below. Change the code and see what happens.

Loading Pyodide... 0%
Python Code Editor
========================================
TUPLE VS SET COMPARISON
========================================

Tuple: (1, 2, 2, 3, 3, 3, 4, 5, 5)
Set: {1, 2, 3, 4, 5}

1. MUTABILITY
Tuple can change? No (TypeError if you try)
Set can change? Yes (add, remove)

2. UNIQUENESS
Tuple has 9 elements (with duplicates)
Set has 5 elements (duplicates removed)

3. ORDER
Tuple[0]: 1 (index access works)
Set[0] would give an error!

4. PERFORMANCE (MEMBERSHIP)
Tuple membership: 0.008000s
Set membership: 0.000001s (faster!)

5. MEMORY USAGE
Tuple size: 120 bytes
Set size: 216 bytes

6. DICTIONARY KEYS
Tuple as key: {(1, 2): 'This works!'}

Tuple vs Set comparison complete!
🏆

You've Got It!

You now understand the key differences between tuples and sets — mutability, uniqueness, ordering, performance, memory, and when to use each. This is a common interview question, so you're ready!

Quick Quiz

Test what you've learned:

1. What is the main difference between a tuple and a set?
2. Which uses less memory: tuple or set?
3. Can a set be a dictionary key?
4. Which is faster for checking if an item exists?
5. What is the correct way to create a single-element tuple?

Frequently Asked Questions

Which is faster: tuple or set? ▼

For membership testing (checking if something exists), sets are much faster. For iteration and ordered access, tuples are faster.

Can I convert a tuple to a set? ▼

Yes! Use set(my_tuple). This removes all duplicates. Use tuple(my_set) to convert back.

Do sets preserve insertion order? ▼

In Python 3.7+, sets preserve insertion order to some extent, but you shouldn't rely on it. Always use tuples if order matters.

Can a tuple contain a set? ▼

Yes, a tuple can contain a set: (1, 2, {3, 4}). But a set cannot contain a tuple that contains a set (nested mutable objects are not hashable).

Which uses less memory: tuple or set? ▼

Tuples use less memory because sets store hash tables for fast lookups. For large datasets, the difference can be significant.

What's a common interview question about tuples and sets? ▼

The most common is: "What's the difference between a tuple and a set?" Answer: Tuples are immutable and ordered; sets are mutable and unordered with no duplicates. "Can you use a set as a dictionary key?" Answer: No.

Where to Go From Here

Now that you understand tuples and sets, check out these related topics:

Tuple vs Dictionary

Compare tuples with dictionaries for fixed vs key-value data.

Learn More →

Dictionary vs Set

Compare dictionaries with sets for key-value vs unique data.

Learn More →

List vs Set

Compare lists with sets for ordered vs unique data.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: List vs Dictionary Next: Tuple vs Dictionary →