Sets Code#

  • Please solve the following questions using Python code.  

Question-1#

Identify the unique names in the list names below (not case-sensitive), and store them in a new list with dictionary order and capitalized.

names = ['Ben', 'ElI', 'Ben', 'Ian', 'MIa', 'Eva', 'Ana', 'Leo',  'Tim', 'liz', 'ben', 'ana', 'ben' ]

Solution

names_cap = [i.capitalize() for i in names]
names_cap = set(names_cap)
names_cap = list(names_cap)
names_cap.sort()

print(names_cap)

Output:

[‘Ana’, ‘Ben’, ‘Eli’, ‘Eva’, ‘Ian’, ‘Leo’, ‘Liz’, ‘Mia’, ‘Tim’]

Question-2#

Remove names that start with a capital letter from the lists below.

  • Store the unique names (not case-sensitive) in a new list, ensuring they are capitalized and ordered.

names1 = ['Ben', 'ElI', 'Ben', 'Ian', 'MIa', 'Eva', 'Ana', 'Leo',  'Tim', 'liz', 'ben', 'ana', 'ben' ]
names2 = ['Max', 'Eli', 'Ben', 'Ian', 'Amy', 'mia', 'Eva', 'anA', 'Leo', 'Joe', 'Liz', 'max', 'iAn' ]

Solution

names = names1 + names2

remove_list = []

for name in names:
    if name[0].isupper():
        remove_list.append(name)
        
names_set = set(names) - set(remove_list)

names_cap = [i.capitalize() for i in names_set]

names_cap = list(set(names_cap))

names_cap.sort()

print(names_cap)

Output:

[‘Ana’, ‘Ben’, ‘Ian’, ‘Liz’, ‘Max’, ‘Mia’]