Syed Naqi
Syed Naqi

Reputation: 41

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")

Upvotes: 0

Views: 48

Answers (2)

Pierce Darragh
Pierce Darragh

Reputation: 2200

This is much easier if you make a function to handle individual cases first.

def convert(item):
    if isinstance(item, str):
        return item.upper()
    if isinstance(item, bool):
        return not item
    if isinstance(item, list):
        return "List"
    if isinstance(item, int) or isinstance(item, float):
        return item + 1
    raise ValueError("invalid type: {}".format(type(item)))

Once we have this, we can just apply a map:

map(convert, my_list)

And if you desperately need it to be a list and not just an iterable, convert it to a list:

list(map(convert, my_list))

Upvotes: 2

roganjosh
roganjosh

Reputation: 13175

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')

Upvotes: 1

Related Questions