Skip to content
Advertisement

Indent-Expected errors while trying to write one-line list comprehension: if-else variants

I am trying to write a list with if-else statements in one line. I’ve followed the instructions in this solution, but I got multiple “indent-Expected” errors.

Here is my code:

initial= [[1,2,3],[],[]]
for block in initial:
    '''
    If block is empty move to the next block
    '''
    if not block: # empty?
        continue # change the block
    elif block: # full?
        packet = block[0]
        # True if there is an empty sublist
        x = [True for i in initial if len(i) == 0]
        # Enter if there is no empty sublist
        if not any(x):
            # Here is the issue
            if packet > max([continue if sublist == block  else sublist[-1] for sublist in initial]):
                continue
        block.remove(packet)
        break # New-one

The issue in this line:

if packet > max([continue if sublist == block  else sublist[-1] for sublist in initial]):

Advertisement

Answer

continue is a reserved keyword in Python so you are getting the error.

You don’t need a continue to skip element.

Further an if without else is complete in list comprehension.

Based on comments, if you just need to skip elements you can just use an if without an else.

Here is a dummy example to show what you need:

initial = [[1, 2], [2, 3], [4, 5]]
block = [1, 2]
res = max([sublist[-1] for sublist in initial if sublist != block]) # just if is enough without else
print(res)
Advertisement