List Comprehension in Python - bug or anything I don't understand?


#1

I noticed that List Comprehension in Python doesn’t work time to time, but only today I’ve reduced it to the minimal sample.

Let’s choose any level, where you have to collect coins. (I’ve done my tests on Keeping Time level – http://codecombat.com/play/level/keeping-time).
My code might look over-complicated but it’s just to show the problem.

First version works as expected, character collects nearest coins.
Sample #1

loop:
    items = self.findItems()
    filtered = [x for x in items]
    item = self.findNearest(filtered)
    if item:
        self.moveXY(item.pos.x, item.pos.y)

Now let’s modify it a bit: all the code starting from filtered = […] we’ll put inside the If statement.
Sample #2 – Doesn’t work

loop:
    items = self.findItems()
    if True:
        filtered = [x for x in items]
        item = self.findNearest(filtered)
        if item:
            self.moveXY(item.pos.x, item.pos.y)

It’s obvious that this code is fully equivalent to first one. But the character doesn’t move at all. Filtered list seems to be empty in the this case.

The code without list comprehension works as intended:
Sample #3

loop:
    items = self.findItems()
    if True:
        item = self.findNearest(items)
        if item:
            self.moveXY(item.pos.x, item.pos.y)

Do you guys have any ideas what’s wrong in the second case?


#2

Actually, it is not empty…

        filtered = [x for x in items]
        self.say(filtered)

says: “[object, Object]”

which is pretty useless, but not “empty”…

follow bug here


#3

@Vlevo, thx for merging these issues. I didn’t check bug tracker @ github
It’s pretty annoying when minor modification of code causes loss of functionality