user764357
user764357

Reputation:

Altering a list using append during a list comprehension

Caveat: this is a straight up question for code-golfing, so I know what I'm asking is bad practise in production

I'm trying to alter an array during a list comprehension, but for some reason it is hanging and I don't know why or how to fix this.

I'm dealing with a list of lists of indeterminite depth and need to condense them to a flat list - for those curious its this question. But at this stage, lets just say I need a flat list of all the elements in the list, and 0 if it is a list.

The normal method is to iterate through the list and if its a list add it to the end, like so:

for o in x:
 if type(o)==type([]):x+=o
 else:i+=o
print i

I'm trying to shorten this using list comprehension, like so.

print sum([
 [o,x.append(o) or 0][type(o)==type([])]
 for o in x
]))

Now, I know List.append returns None, so to ensure that I get a numeric value, lazy evaluation says I can do x.append(o) or 0, and since None is "falsy" it will evaulate the second part and the value is 0.

But it doesn't. If I put x.append() into the list comprehension over x, it doesn't break or error, or return an iteration error, it just freezes. Why does append freeze during the list comprehension, but the for loop above works fine?

edit: To keep this question from being deleted, I'm not looking for golfing tips (they are very educational though), I was looking for an answer as to why the code wasn't working as I had written it.

Upvotes: 5

Views: 11549

Answers (2)

Roberto
Roberto

Reputation: 2786

What about:

y = [element for element in x if type(element) != list or x.extend(element)]

(note that extend will flatten, while append will only add the nested list back to the end, unflattened).

Upvotes: 3

jwodder
jwodder

Reputation: 57490

or may be lazy, but list definitions aren't. For each o in x, when the [o,x.append(o) or 0][type(o)==type([])] monstrosity is evaluated, Python has to evaluate [o,x.append(o) or 0], which means evaluating x.append(o) or 0, which means that o will be appended to x regardless of whether it's a list. Thus, you end up with every element of x appended to x, and then they get appended again and again and again and OutOfMemoryError

Upvotes: 8

Related Questions