Sets

What Are Sets?

  • Sets are used to store multiple items in a single variable. They are one of the four built-in data types in Python used to store collections of data. The other three are List, Tuple, and Dictionary.

Creating a Set:

  • Sets are created using curly brackets {} or the set() constructor.

    python
    myset = {"apple", "banana", "cherry"}
    print(myset)  # Output: {'banana', 'apple', 'cherry'}
    •  Output: {'apple', 'banana', 'cherry'}

Properties of Sets:

  • Unordered: Items do not have a defined order.
  • Unchangeable: Once a set is created, you cannot change its items, but you can remove items and add new items.
  • No Duplicates: Sets cannot have duplicate items.

Examples:

  • Creating a Set:

    python
    thisset = {"apple", "banana", "cherry"}
    print(thisset)  # Output: {'banana', 'apple', 'cherry'}

    Output: {'apple', 'banana', 'cherry'}

  • Duplicate Values:

    python
    thisset = {"apple", "banana", "cherry", "apple"}
    print(thisset)  

    Output: {'apple', 'banana', 'cherry'}

  • Set with Different Data Types:

    python
    set1 = {"apple", "banana", "cherry"}
    set2 = {1, 5, 7, 9, 3}
    set3 = {True, False, False}
    
  • Mixed Data Types:

    python
    set1 = {"abc", 34, True, 40, "male"}
    print(set1) 

     Output: {True, 34, 40, 'male', 'abc'}

Summary:

  • Sets are unordered collections of unique items. They are useful for storing items that must not contain duplicates. Practice creating, adding, removing, and iterating over sets to understand their properties and uses!