Python Novice
Python Novice

Reputation: 121

Having problems with if and else in list comprehensions. I need to make the list value something if the list is empty

I have this:

name_list = [x for x in list]
if not name_list:
    name_list = "n/a"

I want to make it in one line.

I want this:

name_list = ["n/a" if not x else x.text for x in list]

The problem I'm having if that I don't know what to put in the first x of the above code.

How do I check if the list is empty and make the value "n/a" in one line?

Upvotes: 1

Views: 86

Answers (3)

Chris
Chris

Reputation: 22953

You're mistaken here. You don't want a list comprehension. You use list comprehensions when you need to build new lists. That's not what you want to do here. You want to assign a certain value to name_list depending on a condition.

This can be done using Python's or operator. The or operator is short-circuited, and returns the first 'truthy' value it evaluates:

name_list = [x for x in list] or "n\a"

However, I would recommended being careful using the above code, as it can be confusing for people who aren't familiar with it. Depending on your case, it might be better to be more explicit and break the above code into two steps:

tmp = [x for x in list] 
name_list = tmp if tmp else "n\a"

Upvotes: 1

Chen A.
Chen A.

Reputation: 11280

In the first code snippet, if the list is empty you assign a string to it. Not a list. Hence you can't do it with list comprehension, as the latter always returns a list.

You can use other Python builtin feature to achieve that:

name_list = [x.text for x in list] or "n\a"

It will evaluate the first expression first, and if its Falsey (None, False, 0) it will use the other expression - n\a.

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49794

You can simply use or to do that like:

name_list = [x for x in a_list] or "n/a"

or is a short-circuit operator, so it only evaluates the second argument if the first one is false.

Upvotes: 0

Related Questions