Python

 

 

 

 

Python - Set

 

Set in Python is an unordered collection of distict elements. This is a data structure which is like a listbox or dropdown box you see in GUI program.

 

A Python set is a built-in data structure that stores an unordered collection of unique elements. Sets are mutable and can be changed after they are created. However, they do not support indexing, slicing, or other sequence-like behavior, as they are unordered. Elements within a set can be of different data types, but they must be hashable, which means that mutable types like lists and dictionaries cannot be used as elements of a set.

 

To create a set, you can use curly braces {} and separate the elements with commas. Alternatively, you can use the set() constructor, which can accept an iterable (such as a list or tuple) to create a new set. To create an empty set, you must use the set() constructor, as using empty curly braces {} will create an empty dictionary instead.

 

Some of the main features of sets include:

  • Uniqueness: Sets do not allow duplicate elements. If you try to add an element that already exists in the set, it will have no effect on the set's contents.
  • Unordered: The elements in a set have no defined order. This means that you cannot access elements using indices or perform slicing operations.
  • Mutable: Sets can be modified after they are created, allowing you to add or remove elements.
  • Hashable elements: Sets only accept hashable data types as elements, such as integers, floats, strings, and tuples (if they contain hashable elements).

Python provides various built-in methods and functions to manipulate sets, such as:

  • add(): Adds an element to the set.
  • update(): Adds multiple elements from another iterable to the set.
  • remove(): Removes an element from the set. If the element is not found, a KeyError is raised.
  • discard(): Removes an element from the set if it exists, without raising an error if it's not found.
  • pop(): Removes and returns an arbitrary element from the set. If the set is empty, a KeyError is raised.
  • clear(): Removes all elements from the set.
  • len(): Returns the number of elements in the set.
  • issubset(): Checks if one set is a subset of another.
  • issuperset(): Checks if one set is a superset of another.
  • union(): Returns a new set containing all elements from two or more sets.
  • intersection(): Returns a new set containing elements common to two or more sets.
  • difference(): Returns a new set containing elements in the first set that are not in the second set.
  • symmetric_difference(): Returns a new set containing elements that are unique to each of the two sets.

 

 

 

Differences among Array, Set, Dictionary

 

Arrays, sets, and dictionaries are all collection data structures in Python, but they have some key differences in terms of their properties and use cases. Here's a summary of their main differences:

 

Arrays:

  • Arrays are a fixed-size, mutable, and ordered collection of elements, typically of the same data type.
  • Elements can be accessed and modified by their index, allowing for fast and efficient random access.
  • Arrays are not a built-in data structure in Python, but can be used through the array module or other libraries like NumPy.
  • Use cases: Arrays are suitable for situations where you need to store and manipulate elements of the same data type, especially when working with large amounts of numerical data or when you need to perform mathematical operations on the data.

 

Sets:

  • Sets are an unordered collection of unique, hashable elements.
  • Sets do not allow duplicate elements and do not support indexing or slicing.
  • Sets are mutable, and elements can be added or removed after the set is created.
  • Sets are a built-in data structure in Python and can be created using the set() constructor or curly braces {}.
  • Use cases: Sets are suitable for situations where you need to store unique elements, perform membership tests, or carry out mathematical set operations such as unions, intersections, and differences.

 

Dictionaries:

  • Dictionaries store key-value pairs in an unordered collection.
  • Keys must be unique and hashable, while values can be of any data type.
  • Dictionaries are mutable, and key-value pairs can be added, removed, or updated after the dictionary is created.
  • Dictionaries are a built-in data structure in Python and can be created using curly braces {} or the dict() constructor.
  • Use cases: Dictionaries are suitable for situations where you need to store and manipulate data based on keys, such as storing configuration settings, counting word frequencies, or implementing caching mechanisms.

 

 

 

Examples

 

Followings are the list example showing various usages and operations of Set

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Creating a Set : Direct Creation - Example 1
  • Creating a Set : Using set() function - >Example 2
  • Creating a Set : Creating from a String - >Example 3
  • Accessing a Set : Getting one item - >Example 4
  • Getting the length (size) of a List - >Example 5
  • Accessing a Set : Looping through every elements - >Example 6
  • Adding an element : Adding an element to a set - >Example 7
  • Removing an element : Removing an element from a set - >Example 8
  • Set Operation : Intersection - >Example 9
  • Set Operation : difference - >Example 10
  • Set Operation : union - >Example 11

 

 

Examples :

 

< Example 1 >

 

fruits = {"Apple","BlueBerry","Banana","SrawBerry"}

print(fruits)

 

Result :----------------------------------

 

{'SrawBerry', 'Apple', 'BlueBerry', 'Banana'}

 

 

 

< Example 2 >

 

fruits = set(["Apple","BlueBerry","Banana","SrawBerry"])

print(fruits)

 

Result :----------------------------------

 

{'SrawBerry', 'Apple', 'BlueBerry', 'Banana'}

 

 

< Example 3 >

 

words = set("This is a example of creating a Set".split())

print(words)

 

Result :----------------------------------

{'creating', 'This', 'a', 'of', 'Set', 'example', 'is'}

 

 

< Example 4 >

 

fruits = set(["Apple","BlueBerry","Banana","SrawBerry"])

 

// Set does not support direct 'indexing', so you need to convert it to a list

// for direct indexing

print(list(fruits)[2])

 

Result :----------------------------------

 

SrawBerry

 

 

< Example 5 >

 

fruits = {"Apple","BlueBerry","Banana","SrawBerry"}

print(len(fruits))

 

Result :----------------------------------

 

4

 

 

< Example 6 >

 

fruits = {"Apple","BlueBerry","Banana","SrawBerry"}

 

for fruit in fruits :

    print(fruit, ' ', end ='')

 

Result :----------------------------------

 

BlueBerry  Banana  SrawBerry  Apple

 

 

< Example 7 >

 

fruits = {"Apple","BlueBerry","Banana","SrawBerry"}

fruits.add("Grape")

print(fruits)

 

Result :----------------------------------

 

{'BlueBerry', 'Banana', 'Grape', 'SrawBerry', 'Apple'}

 

 

< Example 8 >

 

fruits = {"Apple","BlueBerry","Banana","SrawBerry"}

fruits.remove("Apple")

print(fruits)

 

Result :----------------------------------

 

{'BlueBerry', 'Banana', 'SrawBerry'}

 

 

< Example 9 >

 

A = {"Apple","BlueBerry","Banana","SrawBerry"}

B = {"Mango","Pineapple","Banana"}

 

print(A.intersection(B))

print(B.intersection(A))

 

Result :----------------------------------

 

{'Banana'}

{'Banana'}

 

 

< Example 10 >

 

A = {"Apple","BlueBerry","Banana","SrawBerry"}

B = {"Mango","Pineapple","Banana"}

 

print(A.difference(B))

print(B.difference(A))

 

Result :----------------------------------

 

{'SrawBerry', 'Apple', 'BlueBerry'}

{'Pineapple', 'Mango'}

 

 

< Example 11 >

 

A = {"Apple","BlueBerry","Banana","SrawBerry"}

B = {"Mango","Pineapple","Banana"}

 

print(A.union(B))

print(B.union(A))

 

Result :------------------------------------

 

{'Apple', 'BlueBerry', 'SrawBerry', 'Pineapple', 'Mango', 'Banana'}

{'Pineapple', 'Apple', 'BlueBerry', 'SrawBerry', 'Mango', 'Banana'}

 

 

< Example 16 >