Skip to main content
Practice

Utilizing Values within a Set

A Set is a collection of unordered elements, which means you cannot access specific elements using zero-based index numbers.

However, you can perform various operations such as calculating the sum of all elements, or checking for the presence of a specific element.


Calculating the Sum of Set Elements

To calculate the sum of all elements within a set, you can use the sum() function.

Calculating the sum of set elements
my_set = {1, 2, 3, 4}
sum_of_elements = sum(my_set)

print("sum_of_elements:", sum_of_elements)
# 10

In the above code, sum(my_set) returns the sum of all the elements within the my_set set.


Checking for the Presence of a Specific Element

To verify if a specific element exists within a set, you can use the in keyword.

Checking for element presence in a set
my_set = {1, 2, 3, 4}

# Checking if 2 is in the set
if 2 in my_set:
print("2 exists in the set.")

In the above code, 2 in my_set checks if 2 exists within the my_set set.

If 2 is within my_set, 2 in my_set evaluates to True and the conditional statement is executed.


You can reiterate over each element in the set using a for loop as shown below.

The for loop reiterates over a given sequence (a series of elements like lists, tuples, or strings), performing repetitive tasks on each element.


Iterating over set elements using a for loop
my_set = {1, 2, 3, 4}

for element in my_set:
print(element)
# Output: 1, 2, 3, 4 (order is arbitrary)

In this example, the set named my_set is traversed, and each element is assigned to the variable element, with print(element) executed for each element.

We'll cover loops in more detail in the next lesson.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.