tarikki
tarikki

Reputation: 2319

If list has values, append them to another list, else append predefined value

Suppose I have a list A, which I want to grow depending on some values in list B. I want to append B to A, and in the case B is empty, I want to input a predefined value to indicate this.

if B:
    A.extend(B)
else:
    A.append('no value')

This code does exactly what I want, but my only problem is that it doesn't look very pythonic. I'm pretty sure there must be a way to do this in one line where the if-else statement is in the list comprehension, something like:

A.extend([[x for x in B] if B else 'no value'])

This line almost works, but it in the case A = [] and B = [1], I end up with A = [[1]], which does not work for what I want to do.

Any ideas how to make this work?

Upvotes: 0

Views: 281

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121186

Pass a list with the default value; there is no need for a list comprehension here either:

A.extend(B or ['no value'])

I used or here because an empty list is considered false in a boolean context; it is more compact here and avoids repeating yourself.

The conditional expression version would be:

A.extend(B if B else ['no value'])

Upvotes: 4

Related Questions