[BangPypers] Python List Comprehension Question

Bhargav Kowshik bhargav.kowshik at yahoo.com
Fri Oct 3 18:09:31 CEST 2014


Thank you Kracekumar.

http://docs.python-guide.org/en/latest/writing/gotchas/#what-you-wrote"Python’s default arguments are evaluated once when the function is defined,not each time the function is called." Thank you,
Bhargav.
 

     On Friday, October 3, 2014 9:18 PM, kracekumar ramaraju <kracethekingmaker at gmail.com> wrote:
   
 

 

On Fri, Oct 3, 2014 at 9:04 PM, Bhargav Kowshik <bhargav.kowshik at yahoo.com.dmarc.invalid> wrote:

Nice! Thank you very much Anand.But, I still don't know what is happening.Please point me to a resource to understand what is happening.



A common beginner mistake. More of such gotcha can be found here http://docs.python-guide.org/en/latest/writing/gotchas/ .
 
** Program **

def flat_it(values, result=list()):
    for v in values:
        if isinstance(v, list):
            flat_it(v, result)
        else:
            result.append(v)
    return result

x = [[1, 2, [3, 7]], 4]

print('Input: {0}'.format(x))
print('Output 1: {0}'.format(flat_it(x)))
print('Output 2: {0}'.format(flat_it(x)))
print('Output 3: {0}'.format(flat_it(x, list())))

** Output **
Input: [[1, 2, [3, 7]], 4]
Output 1: [1, 2, 3, 7, 4]
Output 2: [1, 2, 3, 7, 4, 1, 2, 3, 7, 4]
Output 3: [1, 2, 3, 7, 4]

Thank you,
Bhargav.


     On Friday, October 3, 2014 8:48 PM, Anand Chitipothu <anandology at gmail.com> wrote:



 On Fri, Oct 3, 2014 at 8:26 PM, Bhargav Kowshik <bhargav.kowshik at yahoo.com.dmarc.invalid> wrote:

We could use what Anand talked about at Pycon India about handling the headers in first row of a CSV.In this scenario, instead of default for result being None and checking if None everytime, we could have the default value an empty list.

def flat_it(values, result=list()):
    for v in values:
        if isinstance(v, list):
            flat_it(v, result)
        else:
            result.append(v)
    return result

x = [[1, 2, [3, 4, 5, 6, 7]], 4]
print x
print flat_it(x)


Thats a pitfall! Try calling flat_it once again and see what you get.
Anand



_______________________________________________
BangPypers mailing list
BangPypers at python.org
https://mail.python.org/mailman/listinfo/bangpypers




-- 
Thanks & Regards
kracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com

 
   


More information about the BangPypers mailing list