Sets in Python - Python Certification Program

Published: 08 January 2023
on channel: Indian Servers University
42
1

In Python, a set is an unordered collection of unique elements. It is a mutable data type, meaning that you can add or remove elements from a set after it is created.

A set is created by placing a comma-separated sequence of elements in curly braces {}, or by using the set() function. For example:
set1 = {1, 2, 3}
set2 = {"a", "b", "c"}
set3 = set([1, 2, 3, 4, 5])


Sets do not support indexing or slicing, since they are unordered collections.

To add an element to a set, you can use the add() method.

set1.add(4)
set1
{1, 2, 3, 4}


To remove an element from a set, you can use the remove() method. If the element is not found in the set, it will raise a KeyError.
set1.remove(2)
set1
{1, 3, 4}

You can also use the discard() method to remove an element from a set. If the element is not found in the set, it will not raise an exception.
set1.discard(2)
set1
{1, 3, 4}

You can use the len() function to get the number of elements in a set.
len(set1)
3



Powered by www.IndianServers.com
Indian Servers University


On this page of the site you can watch the video online Sets in Python - Python Certification Program with a duration of hours minute second in good quality, which was uploaded by the user Indian Servers University 08 January 2023, share the link with friends and acquaintances, this video has already been watched 42 times on youtube and it was liked by 1 viewers. Enjoy your viewing!