12/15 purify


#1
def purify(num):
    for number in num:
        if number%2 == 0:
            number = list(str(number))
            print(number)


purify([1,8,9,6,5,3,4,6,5,8,8,9,9,2,3,1,5])

o/p -
['8'] ['6'] ['4'] ['6'] ['8'] ['8'] ['2']

How can i change the output to a single list?


#2

Not a good idea to re-use a variable name inside a loop.


#3

what should i do to merge multiple list into a single list?


#4

Start by not creating them in the first place. Well, in truth you are not creating them but only printing them. Nothing is being created in the code sample we’re being given.

Aside

The most useful functions are the ones that return something we can work with later or in the course of things. Printing is only a means of visual confirmation that the computation is happening, but where does the data go? Poof! Gone.

Cache computed results, then print at one’s leisure.


#5

D**n, I see what you’re going through, finally!.

>>> def purify(s):
	return list(filter(lambda x: not x % 2, s))

>>> purify([1,8,9,6,5,3,4,6,5,8,8,9,9,2,3,1,5])
[8, 6, 4, 6, 8, 8, 2]
>>> 

We’re jumping the gun, though, aren’t we? Anonymous functions haven’t come up yet, and we still haven’t confirmed a use for list at this point, or even str, when examining the sample code.


#6

I am not aware of the lambda function till now so i dont know how it is used. :confused:


#7

As expected, so pass on the alarm. Belay, belay. I’m just as confused about your code as you are about mine.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.