What is the difference between a list and a set in Python?

QuestionsQuestions8 SkillsProPython Data StructuresAug, 11 2025
0272

In Python, the main differences between a list and a set are:

  1. Order:

    • List: Maintains the order of elements. You can access elements by their index.
    • Set: Unordered collection. Elements do not have a specific order, and you cannot access them by index.
  2. Duplicates:

    • List: Allows duplicate elements. You can have the same value multiple times.
    • Set: Does not allow duplicate elements. Each value must be unique.
  3. Mutability:

    • Both lists and sets are mutable, meaning you can change their contents after creation (e.g., adding or removing elements).
  4. Performance:

    • List: Searching for an element can be slower (O(n) time complexity) because it may require iterating through the entire list.
    • Set: Searching for an element is generally faster (O(1) average time complexity) due to its underlying hash table implementation.

Example

# List example
my_list = [1, 2, 2, 3, 4]
print(my_list)  # Output: [1, 2, 2, 3, 4]

# Set example
my_set = {1, 2, 2, 3, 4}
print(my_set)  # Output: {1, 2, 3, 4} (duplicates removed)

Use lists when you need ordered collections with possible duplicates, and use sets when you need unique elements and do not care about order.

0 Comments

no data
Be the first to share your comment!