Exercise 208

Write a program in Python that remove an element from a given set A without using the discard() or remove() methods.

Solution

# define a set A
A = { 'a', 'b', 'c', 'd' }
# remove the 'd' element without using either the remove() method or the discard() method

#initialize an empty set B
B = set({})

# loop through the elements of A
for x in A:
if x!= 'd':
B.add(x)

print("A{'d'} = ", B)
# output: A{'d'} = {'b', 'c', 'a'}
Younes Derfoufi
my-courses.net

Leave a Reply