Posts

Showing posts with the label Sets

Python Programming Language - Sets

Image
A set is an unordered, unique sequence. A set is declared using comma-separated elements inside curly braces: twd = { "Carl" , "Rick" , "Daryl" , "Carl" } print(twd)     # {'Rick', 'Carl', 'Daryl'} Please note that the print function prints the element "Carl" once, but the set definition has this element in it twice because the set only has unique values. To create a set from another set of elements, such as a list, you can pass the list to the set() function, which will return the set: twd = [ "Carol" , "Rick" , "Daryl" ] # List users = set(twd) print(users)     # {'Rick', 'Daryl', 'Carol'} The set function can be used to make an empty set: twd = set() To get the length of a set, use the built-in len() function: twd = { "Carl" , "Rick" , "Carol" } print(len(twd))       # 3 Adding elements The add() method is used to add a single