


The requirement of immutability follows from the way how do computers represent sets in memory. Unlike arrays, where the elements are stored as ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored. A list of lists in pythonis a list that contains lists as its elements. In particular, list cannot be an element of a set (but tuple can), and another set cannot be an element of a set. Mutable (changeable) data types cannot beĮlements of the set.

The set elements are usually not stored in order of appearance in the set this allows checking if an element belongs to a set faster than just going through all the elements of the set).Īny immutable data type can be an element of a set:Ī number, a string, a tuple. List, the order of elements in a set is undefined (moreover, Unlike arrays, where the elements are stored as ordered The major and most important difference between sets and list is that unlike lists, Sets cannot store multiple occurrences of the same elements. Besides that, you can check if an element belongs to a set. The elements of the set, you can perform standard operations on sets You can add and delete elements of a set, you can iterate Just like we use list comprehensionto create lists, we can use set comprehension instead of for loop to create a new set and add elements to it. add ( element) Parameters The set add () takes an element parameter, which needs to be added to the set. The set add () is an inbuilt Python method that adds a given element to a set if the element is not present in the set. Of various elements the order of elements in a set is undefined. Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples. To append a single element in Python Set, use the add () method.
