Sets in Python

 Sets in Python


Sets are a collection of unique elements, meaning that each element can only appear once in the set. Sets are defined using curly braces {} or the set() function. Here's an example of defining a set and performing some basic operations:


python


numbers = {1, 2, 3, 4, 5}

print(numbers)


numbers.add(6)

print(numbers)


numbers.remove(2)

print(numbers)


set1 = {1, 2, 3}

set2 = {3, 4, 5}


print(set1.union(set2))

print(set1.intersection(set2))

print(set1.difference(set2))

In this example, we define a set called numbers with some elements, and print it using the print function. We then add a new element to the set using the add method, and remove an element using the remove method.


We then define two sets set1 and set2, and use some set operations to combine, intersect, and find the difference between the two sets.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...