Skip to content
Advertisement

Inline for loop

I’m trying to learn neat pythonic ways of doing things, and was wondering why my for loop cannot be refactored this way:

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1]

for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

vm[p.index(max(p))] = i

I tried replacing the for loop with:

[p.append(q.index(v)) if v in q else p.append(99999) for v in vm]

But it doesn’t work. The for v in vm: loop evicts numbers from vm based on when they come next in q.

Advertisement

Answer

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement