Introduction to Python Sets

Discover Python sets, a built-in data type used to store multiple items in a single variable. Learn about the characteristics of sets, including their unordered and unindexed nature, and how they differ from other data types like lists, tuples, and dictionaries. Note that while set items are unchangeable, you can still add or remove items.



Set

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Example

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

  {'apple', 'banana', 'cherry'}
              

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

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

  {'apple', 'banana', 'cherry'}
              

Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

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

  3
              

Set Items - Data Types

Set items can be of any data type.

Example

  set1 = {"apple", "banana", "cherry"}
  set2 = {1, 5, 7, 9, 3}
  set3 = {True, False, False}
  
  print(set1)
  print(set2)
  print(set3)
              
Output

  {'apple', 'banana', 'cherry'}
  {1, 3, 5, 7, 9}
  {False, True}
              

From Python's Perspective

From Python's perspective, sets are defined as objects with the data type 'set'.

Example

  myset = {"apple", "banana", "cherry"}
  print(type(myset))
              
Output

<class 'set'>
              

The set() Constructor

It is also possible to use the set() constructor to make a set.

Example

  thisset = set(("apple", "banana", "cherry"))
  print(thisset)
              
Output

  {'apple', 'banana', 'cherry'}