0

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']

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.