Python Set
Set is an unordered and unindexed collection of items.
Create a Set
Sets are written with curly brackets.
Example
ages = {26,56,90} print(ages) Output {56,26,90}
Access Set Elements
We cannot access items in set by referring to an index because sets are unordered and unindexed,the items has no index.
Loop through Tuple
We can loop through the set items by using a for loop.
Example
fruit={"apple","banana","cherry"} for x in fruit: print(x) Output apple banana cherry
Set Length
To determine how many items a set has, use the len() function.
Example
> fruit={"apple","banana", "cherry"} print(len(fruit)) Output 3
Add Items in Set
To add one item to a set,use add() method.
Example
fruits={"apple","banana","cherry"} fruits.add("orange") print(fruits) Output: {'apple','banana','orange','cherry'}
To add more than one items in set,use update() method.
Example
fruits={"apple","banana","cherry"} fruits.update(["orange","mango"]) print(fruits) Output: {'apple','banana','cherry','orange','mango',}
Remove Items in Set
To remove an item in a set,use the remove()
method or the discard() method.
Example
fruits={"apple","banana","cherry"} fruits.remove("banana") print(fruits) Output: {'apple','cherry',}
Using discard() method.
Example
fruits={"apple","banana","cherry"} fruits.discard("banana") print(fruits) Output: {'apple','cherry',}
Set Constructor
Using set() constructor,we can make a set.
Example
> thisset=set(("apple","banana","cherry")) print(thisset) Output: {'cherry','apple','banana'}