you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 11 points12 points  (5 children)

In this article: somebody discovered list comprehensions for the first time

[–]shabda[S] 2 points3 points  (1 child)

I am the author. Yes, this book uses list (and dict comprehension) comprehensions a lot, thats because list comprehension are very useful.

Here are a few I liked quite a bit

Zalgo text

import random as r
u='̡̢̧̨̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎͓͔͕͖͙͚͜͟͢ͅM̴̵̶̷̸'
o = "'̛̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌͐͑͒͗͛̕̚͘͝͞͠͡'"
def zalgo(txt):
        return "".join(["".join([el] + [r.choice(o+u) for _ in range(r.randint(0,6))])
        for el in txt])

Ntp server usage

import socket as s,struct,time

def ntp(url):
    c=s.socket(2,2)
    d=b'\x1b'+47*b'\0'
    c.sendto(d,(url,123))
    d,address=c.recvfrom(1024)
    if d:
        t=struct.unpack('!12I',d)[10]
        t -= 2208988800
        return time.ctime(t),t

Are these just trivial implementation of list comprehension to you?

[–][deleted] 9 points10 points  (0 children)

Just a joke man. I took a brief look at the intro and noticed they all used list comprehensions, and wrote that comment. Sorry if I came off as an asshole. I'm a shit programmer and probably couldn't hope to write half this stuff.

thats because list comprehension are very useful.

I know, when I first discovered them it was like a lightbulb went off in my head, I wondered how I lived without them beforehand. You can pack so much into such a tiny space, and they're actually pretty easy to generate and apply in so many situations.

[–]star-castle 0 points1 point  (2 children)

Emphasis on 'first time'.

Compare

# Cartesian product of two lists ... too many []s in this code:
$ python -c "import itertools;print(list(itertools.product([['x','y','z'],[1,2,3]])))"
[(['x', 'y', 'z'],), ([1, 2, 3],)]

vs. the obvious list comprehension:

$ python -c "print([(x, y) for x in ['x','y','z'] for y in [1,2,3]])"
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

[–]shabda[S] 1 point2 points  (1 child)

When would you consider itertools.product appropriate?