nia4life
nia4life

Reputation: 363

Excluding Python Lists With Empty Values

I have two lists, if list has data, I want to create a variable and assign it a name. If not, I want to disregard it. I then want to combine the list names into one list.

I'm having difficulty returning an empty value if there is no data in the list.

countries = ['America', 'France']
cities = []

if len(countries) != 0:
    country_name = 'country'
else:
    country_name = None
if len(cities) != 0:
    city_name = 'city'
else:
    city_name = None

region_names = [country_name, city_name]

Getting:

['country', None]

Want:

['country']

Upvotes: 0

Views: 37

Answers (1)

JJ Hassan
JJ Hassan

Reputation: 395

The reason this isn't working the way you want is None is still a NoneType object. So you can have a list of NoneType objects, or NoneType objects mixed with other types such as strings in your example.

If you wanted to keep the structure of your program similar, you could do something like

countries = ['America', 'France']
cities = []
region_names = []

if len(countries) != 0:
    region_names.append('country')

if len(cities) != 0:
    region_names.append('city')

in this example we declare region_names up front and only append to the list when our conditions are met.

Upvotes: 2

Related Questions