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 List vs Set: What's the Difference?

Python List vs Set - Complete Comparison

Learn the key differences between Python lists 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:
  • Lists vs Sets – What's the Big Difference?
  • Uniqueness: The Biggest Difference
  • Ordering: Lists Keep Order, Sets Don't
  • Performance: Which Is Faster?
  • Mutability: Both Can Change
  • Available Methods
  • 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
  • Uniqueness — lists allow duplicates, sets don't
  • Ordering — lists keep order, sets don't
  • Performance — which one is faster for what
  • Mutability — both can change
  • Methods — what you can do with each
  • When to use — choosing the right one

Lists vs Sets – What's the Big Difference?

If you've worked with Python for a while, you've probably used both lists and sets. They look similar, but they're built for different purposes.

The short answer is: lists keep order and allow duplicates, sets don't. But there's a lot more to it than that. Let's break it down.

💡 Here's the thing: The choice between a list and a set affects performance, memory, and how you work with your data. Choose wisely!

Uniqueness: The Biggest Difference

1

Lists Allow Duplicates, Sets Don't

This is the most important difference. A list can have duplicate values. A set automatically removes duplicates.

# List — can have duplicates
my_list = [1, 2, 2, 3, 3, 3, 4]
print(f"List: {my_list}")  # [1, 2, 2, 3, 3, 3, 4]
print(f"List length: {len(my_list)}")  # 7

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

# Why this matters:
# Use a list when duplicates are okay (e.g., shopping cart)
# Use a set when you need unique items (e.g., unique visitors)

What this means for you:

  • Lists — keep everything, even duplicates
  • Sets — only keep unique values
  • Sets are great for removing duplicates

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

Ordering: Lists Keep Order, Sets Don't

2

Lists Are Ordered, Sets Are Unordered

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

# List — preserves order
my_list = ["apple", "banana", "cherry"]
print(my_list[0])  # apple — index works!
print(my_list[1])  # banana
print(my_list[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 list when order matters (e.g., playlist)
# Use a set when order doesn't matter (e.g., tags)

Key point:

  • Lists — ordered, indexable
  • Sets — unordered, not indexable
  • If order matters, use a list

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

Performance: Which Is Faster?

3

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 list, especially for large data.

import time

# Create large data
big_list = list(range(1000000))
big_set = set(range(1000000))

# Test membership in list
start = time.time()
999999 in big_list
list_time = time.time() - start

# Test membership in set
start = time.time()
999999 in big_set
set_time = time.time() - start

print(f"List membership: {list_time:.6f}s")
print(f"Set membership: {set_time:.6f}s")

# Output example:
# List membership: 0.010000s
# Set membership: 0.000001s

# Sets are MUCH faster for checking if something exists!

Performance summary:

  • Sets — much faster for membership testing
  • Lists — 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)

Mutability: Both Can Change

4

Both Lists and Sets Are Mutable

Unlike tuples, both lists and sets can be changed after creation. You can add, remove, or modify elements.

# List — mutable
my_list = [1, 2, 3]
my_list[0] = 10    # Change
my_list.append(4)  # Add
my_list.remove(2)  # Remove
print(my_list)     # [10, 3, 4]

# Set — mutable
my_set = {1, 2, 3}
my_set.add(4)      # Add
my_set.remove(2)   # Remove
print(my_set)      # {1, 3, 4}

# Both can change, but they change differently:
# Lists keep order when changing
# Sets don't care about order

Key point:

  • Both lists and sets are mutable
  • Lists maintain order when modified
  • Sets don't care about order

Available Methods

5

What You Can Do With Each

Lists and sets have different methods because they're used for different things.

# List methods
my_list = [1, 2, 3]
my_list.append(4)      # Add to end
my_list.insert(1, 10)  # Insert at position
my_list.pop()          # Remove last
my_list.sort()         # Sort
my_list.reverse()      # Reverse
print(my_list)         # [1, 10, 3, 4]

# Set methods
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
print(my_set)          # {1, 3, 4}

# Set methods are more about set operations
# List methods are more about ordering

Key difference:

  • Lists — methods for ordering (sort, reverse, insert)
  • Sets — methods for set operations (union, intersection, difference)
  • Choose based on what you need to do

When to Use Each

6

Which One Should You Choose?

# Use lists when:
# 1. Order matters
shopping_list = ["milk", "eggs", "bread"]
shopping_list.append("butter")  # Adds to end

# 2. You need duplicates
scores = [85, 92, 85, 78]  # Multiple 85s are fine

# 3. You need to access by index
first_score = scores[0]

# 4. You need to sort or reverse
scores.sort()

# 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. Order doesn't matter
tags = {"python", "tutorial", "beginner"}

# 4. You need set operations
all_tags = {"python", "java", "c++"}
python_tags = {"python", "flask"}
common = all_tags.intersection(python_tags)

Simple rule of thumb:

  • Use lists — when order or duplicates matter
  • Use sets — when uniqueness or fast lookups matter
  • When in doubt, ask: "Does order matter?"

Quick Summary Table

7
Feature List Set
Duplicates Allowed ✅ Not Allowed ❌
Order Preserved ✅ Not Preserved ❌
Index Access ✅ Yes ❌ No
Membership Check Slow (O(n)) Fast (O(1)) ✅
Mutability Mutable ✅ Mutable ✅
Memory Smaller ✅ Larger
Best For Ordered data with duplicates Unique values, fast lookups

Common Mistakes

8

Things to Watch Out For

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 list for ordered data
my_list = ["apple", "banana", "cherry"]
print(my_list[0])  # apple

Using a List for Fast Lookups

# WRONG — list membership is slow for large data
my_list = list(range(1000000))
# if 999999 in my_list:  # Slow!

# CORRECT — use a set for fast lookups
my_set = set(range(1000000))
if 999999 in my_set:  # Fast!

Assuming Set Order Is Consistent

# WRONG — relying on set order
my_set = {1, 2, 3}
# The order may vary between runs!

# CORRECT — use sorted() if you need order
for item in sorted(my_set):
    print(item)  # 1, 2, 3

Quick Check: What's the most common mistake with sets? (Answer: Assuming they preserve order)

Try It Yourself

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

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

List: [1, 2, 2, 3, 3, 3, 4, 5, 5]
Set: {1, 2, 3, 4, 5}

1. UNIQUENESS
List has 9 elements (with duplicates)
Set has 5 elements (duplicates removed)

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

3. PERFORMANCE (MEMBERSHIP)
List membership: 0.008000s
Set membership: 0.000001s

4. REMOVING DUPLICATES
Original: [1, 2, 2, 3, 3, 3, 4, 5, 5]
Unique: [1, 2, 3, 4, 5]

5. WHEN TO USE
Use LIST when: order matters, duplicates are okay, you need indexing
Use SET when: duplicates not allowed, fast lookups needed, order doesn't matter

List vs Set comparison complete!
🏆

You've Got It!

You now understand the key differences between lists and sets — uniqueness, ordering, performance, 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 list and a set?
2. Do sets preserve order?
3. Which is faster for checking if an item exists?
4. Can you access a set element by index?
5. When should you use a set instead of a list?

Frequently Asked Questions

Which is faster: list or set? ▼

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

Can I convert a list to a set? ▼

Yes! Use set(my_list). This removes all duplicates. Use list(my_set) to convert back.

Does a set preserve insertion order? ▼

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

Why are sets faster for membership testing? ▼

Sets use hash tables, which allow O(1) lookup time. Lists use arrays, which require O(n) time to search.

Can a set contain duplicate values? ▼

No, sets automatically remove duplicates. If you try to add a duplicate, it will be ignored.

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

The most common is: "What's the difference between a list and a set?" Answer: Lists allow duplicates and preserve order, sets don't. And "Which is faster for membership testing?" Answer: Sets.

Where to Go From Here

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

List vs Dictionary

Compare lists with dictionaries for key-value data.

Learn More →

Tuple vs Set

Compare tuples with sets for immutable vs unique data.

Learn More →

Dictionary vs Set

Compare dictionaries with sets for key-value 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 Tuple Next: List vs Dictionary →