Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to do something like this:

a = some_funct()
b = [ 1, a if a is not None ]

The list b should be one element long if a is None, and two elements long if a is not None. Is this possible in Python or do I have to use a separate if check followed by add()?

share|improve this question
2  
How about b = [1]; if a is not None: b.append(a)? – Psidom 18 hours ago
    
Alternatively, b = [x for x in (1, a) if x is not None] ... but check-then-append is going to be more readable. – Zero Piraeus 18 hours ago
    
b=[1];a and b.append(a) ??? – Skycc 18 hours ago

Doesn't look the best, but you could do

b = [1] + ([a] if a is not None else [])

Of course, it would be better to check as it increases code readability.

share|improve this answer
a = some_funct()
b = [ 1, a ] if a is not None else [1]
share|improve this answer

You can do this using list comprehension

b = [x for x in (1, a) if x is not None]

The tuple (1, a) is the total set, b will become a list of all elements in that total set which are not None

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.