Syed Naqi Syed Naqi - 1 month ago 8
Python Question

making a copy of the list but with following changes:

I'm writing a function that takes as a parameter a list but returns a copy of the list with following changes:
• Strings have all their letters converted to upper-case
• Integers and floats have their value increased by 1
• booleans are negated (False becomes True, True becomes False)
• Lists are replaced with the word ”List”
this function should leave the original input unchanged

This is what I have done so far but I'm not sure how can I add all of these to an empty list, here is my program:

name = [1, 2, "abc123", True, [1, 2, 3]]

new_list = [ ]

for element in name:

if(type(element) == str):
for i in element:
if(i.isalpha()):
element = element.upper()
new_list += element
#print(new_list)
print(element)

elif(type(element) == int):
element = element + 1
print(element)

elif(type(element) == bool):
print(not(element))
else:
print("list")

Answer

you were so close and fell down on the last hurdle. Just use append to add to the empty list.

name = [1, 2, "abc123", True, [1, 2, 3]]

new_list = [ ]

for element in name:

    if(type(element) == str):
        for i in element:
            if(i.isalpha()):
                element = element.upper()

        new_list.append(element)

    elif(type(element) == int):
        element = element + 1
        new_list.append(element)

    elif(type(element) == bool):
        new_list.append(not element)
    else:
        new_list.append('list')