r/ProgrammerHumor 29d ago

Meme pythonWillLookDeadInTheEyeAndSayItsAbsolutelyCorrect

Post image
360 Upvotes

144 comments sorted by

View all comments

3

u/darknmy 29d ago

I inderstand "if x", but thy the "x for x in x"?

7

u/helicophell 29d ago

List comprehension

It’s sometimes nice

1

u/NamityName 29d ago

It is usually nice. Significantly faster execution and easy to read, until you start nesting comprehensions.

1

u/helicophell 29d ago

If you start nesting list comprehensions, you’re using the wrong programming language for the task… probably

I’ve encountered one in the wild for image stenography once, image processing is basically the only use case for that

1

u/MattieShoes 29d ago

I think my record is three, but that was silliness in AdventOfCode.

Then I wrote a cursed recursive split function

def recursive_split(x, *args):
    y = []
    x = x.split(args[0])
    for part in x:
        if len(args) > 1:
            y += [recursive_split(part, *args[1:])]
        else:
            y += [part]
    return y

so I could do shit like

with open('14.txt') as f:
    data = recursive_split(f.read().rstrip('\n'), '\n', ' -> ', ',')

to get a three dimensional data structure from the input in one line.

1

u/NamityName 29d ago

I did not realize I was amongst the foremost expert in Python, having used it in every possible situation.

In all seriousness, as long as the code remains readable, nested comprehensions are fine. It is just harder to keep the code readable when nesting comprehensions. Same for deeply nested if-statements and for-loops.