Sets in Python - Python Certification Program

Publicado el: 08 enero 2023
en el canal de: 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


En esta página del sitio puede ver el video en línea Sets in Python - Python Certification Program de Duración hora minuto segunda en buena calidad , que subió el usuario Indian Servers University 08 enero 2023, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 42 veces y le gustó 1 a los espectadores. Disfruta viendo!