简体   繁体   中英

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.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM