Proposed new syntax

Rustom Mody rustompmody at gmail.com
Mon Aug 14 00:06:08 EDT 2017


On Monday, August 14, 2017 at 4:26:06 AM UTC+5:30, Gregory Ewing wrote:
> Steve D'Aprano wrote:
> 
> > Python's comprehensions are inspired by Haskell's, but we made different choices
> > than they did: we make the fact that a comprehension is a loop over values
> > explicit, rather than implicit, and we use words instead of cryptic symbols.
> 
> The presence of the word "for" in the comprehension syntax doesn't
> by itself imply that the values are generated by a sequential loop.
> 
> Comprehensions in Python are intended to be read declaratively.
> The definition in terms of an expansion into nested loops may

Thanks for speaking up Greg [Creator of comprehensions in python 2??]


Here's a bunch of different ways in which a mapping comprehension could be implemented:

def sq(x): return x*x
Just a trivial example

def simple(f, l):
    r = []
    for i in range(0,len(l)):
        r.append(f(l[i]))
    return r

def backwards(f,l):
    r = []
    for i in range(len(l)-1,-1,-1):
        r.insert(0,f(l[i]))
    return r

def randmap(f,l):
    """ Map in random order """
    from random import shuffle
    r = []
    index = list(range(0,len(l)))
    shuffle(index)

    r = [None] * len(l)
    for i in index:
        r[i] = f(l[i])
    return r

    
def inplace(f, l, lb, le, res): #, rb):
    """ Helper function: Maps subslice (lb,le) of input l onto (into) output res, with
subslice rb,re"""
    for i in range(lb,le):
        res[i] = f(l[i])
    return None # Side-effecting into res

def parprequel0(f,l):
    """Illustrative trivial prequel to parallelizing version"""
    r = [None] * len(l)
    inplace(f,l,0,len(l),r)
    return r
    
def parprequel1(f,l):
    """Illustrative prequel to parallelizing version
with 2-way split"""
    r = [None] * len(l)
    inplace(f,l, 0,         len(l)//2, r)
    inplace(f,l, len(l)//2, len(l),    r)
    return r

def par(f,l):
    """Illustrative prequel to parallelizing version
with 2-way split"""
    from threading import Thread
    r = [None] * len(l)
    t1 = Thread(target=inplace, args = (f,l, 0,         len(l)//2, r))
    t2 = Thread(target=inplace, args = (f,l, len(l)//2, len(l),    r))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    return r



More information about the Python-list mailing list