shadowrain
shadowrain

Reputation: 163

Mapping list to list in python

Write a function named compute below that:

Also, how can I use map function to return the values as a list (not a map_object) in ONE single line?

for example to return something from:

map_compute(['crew', '321', 12, ['x'], True])

to :

['werc', '123', 144, None, None]

Upvotes: 3

Views: 587

Answers (2)

ggorlen
ggorlen

Reputation: 56885

Since types int/float and str are disjoint, you can use elif to skip evaluating the second block which ensures that the else is logically connected to the top if. The problem is that if the first if block executes, else: return None will execute before the intended return x is reached because it's dependent only on the truth value of the if type(value) == str: block.

I always add a blank line above if blocks to show visually that they're logically separate from anything above.

The intermediate value x is unnecessary. Additionally, Python will return None if you don't specify a return type.

Use the map function to apply a function such as compute to each element in a list. map returns an iterator, so you'll need to convert that to a list for printing if you don't plan on iterating over it directly.

def compute(value):
    if type(value) == int or type(value) == float:
        return value ** 2
    elif type(value) == str:
        return value[::-1] 

print(list(map(compute, ['crew', '321', 12, ['x'], True])))

Result:

['werc', '123', 144, None, None]

You can also use a list comprehension to perform a mapping operation:

print([compute(x) for x in ['crew', '321', 12, ['x'], True]])

This is often preferable to the map function for cases when filtering is necessary in addition to a mapping or the mapping operation is easily inlined.

Upvotes: 2

Shivam Gupta
Shivam Gupta

Reputation: 201

You should use this code. In this code, we map example list with the function compute.

In Map function, it iterate over 'example' list and one by one, iterated value from list will call function 'compute(value)' and get the return value. Finally, we convert the map object to list.

def compute(value):
    print(type(value), value)
    if type(value) == int or type(value) == float:
        x = value **2
    elif type(value) == str:
        x = value[::-1]
    else:
        return None
    return x

example = ['crew', '321', 12, ['x'], True]
map_output = list(map(compute, example))
print(map_output)

OUTPUT:

['werc', '123', 144, None, None]

Upvotes: 2

Related Questions