WHAT IS Set Data Type Explain With Example?

//

Heather Bennett

WHAT IS Set Data Type Explain With Example?

A set is a data type in programming that is used to store a collection of unique elements. It is typically used when we want to perform operations such as adding, removing, or checking for the presence of an element in a collection without worrying about duplicate values.

Creating a Set

To create a set in most programming languages, you can use the set keyword followed by curly braces {}. Within the curly braces, you can add elements separated by commas. Let’s take an example:

set fruits = {'apple', 'banana', 'orange'}

In this example, we have created a set called fruits with three elements: apple, banana, and orange.

Adding Elements to a Set

You can add an element to a set using the add() method. Let’s see an example:

fruits.add('mango')

In this example, we added the element ‘mango’ to the fruits set.

Removing Elements from a Set

You can remove an element from a set using the remove() method.remove(‘banana’)

In this example, we removed the element ‘banana’ from the fruits set.

Determining if an Element is Present in a Set

You can check if an element is present in a set using the in keyword. Let’s see an example:

if 'apple' in fruits:
    print('The set contains apple')

In this example, we checked if the element ‘apple’ is present in the fruits set and printed a message accordingly.

Iterating Over a Set

You can iterate over the elements of a set using a for loop. Let’s see an example:

for fruit in fruits:
    print(fruit)

In this example, we iterated over each element in the fruits set and printed it.

Merging Sets

You can merge two sets using the union() method. Let’s see an example:

more_fruits = {'kiwi', 'pineapple'}
all_fruits = fruits.union(more_fruits)
print(all_fruits)

In this example, we merged the fruits set with the more_fruits set to create a new set called all_fruits.

In conclusion,

A set data type is a useful tool for storing collections of unique elements. It allows for efficient operations such as adding, removing, and checking for the presence of an element. By understanding how to create, modify, and manipulate sets, you can enhance your programming skills and solve various problems efficiently.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy