RC-
RC-

Reputation: 163

trying to see if a variable is included in a list in django

I am trying to find if a selected country is in a list of tuples by using the following command in my view:

if second_tier.profile.country in COUNTRIES:

if I print second_tier.profile.country I have CA and when I print COUNTRIES I get:

(('GB', 'United Kingdom'), ('AU', 'Australia'), ('AT', 'Austria'), ('BE', 'Belgium'), ('CA', 'Canada'), ('DK', 'Denmark'), ('FI', 'Finland'), ('FR', 'France'), ('DE', 'Germany'), ('HK', 'Hong Kong'), ('IE', 'Ireland'), ('IT', 'Italy'), ('LU', 'Luxembourg'), ('NL', 'Netherlands'), ('NZ', 'New Zealand'), ('NO', 'Norway'), ('PT', 'Portugal'), ('SG', 'Singapore'), ('ES', 'Spain'), ('SE', 'Sweden'), ('CH', 'Switzerland'), ('US', 'United States'))

So the if statement is supposed to return True, however it comes back as False.

Upvotes: 4

Views: 108

Answers (2)

sandes
sandes

Reputation: 2267

You have a tuple of tuples, then you need to iterate in COUNTRIES.

>>> for x in COUNTRIES:
...     if second_tier.profile.country in x:
...         print ("ok")

Upvotes: 2

RoadRunner
RoadRunner

Reputation: 26315

You currently searching for a string in a tuple of tuples. You need to make sure COUNTRIES is all strings to make this work. You can use some simple list comprehensions to transform your nested tuples.

Using tuple unpacking:

COUNTRIES = [x, _ for x in COUNTRIES]

Using indexing:

COUNTRIES = [x[0] for x in COUNTRIES]

Which takes the first element(country) from each of the tuples and puts them in a list.

Then you can do:

if second_tier.profile.country in COUNTRIES:

and it will return True.

Alternatively you could just loop over COUNTRIES and match second_tier.profile.country explicitly:

for country, _ in COUNTRIES:
    if second_tier.profile.country == country:
        return True

You could also use any() here:

any(second_tier.profile.country == x for x, _ in COUNTRIES)

Which returns True is any match was found.

Note: Since your just doing a simple lookup, you could convert the COUNTRIES to a set, which will allow a O(1) lookup instead of a O(N) lookup.

I also used _ above to discard values that are not needed, such as the second item for each tuple.

Upvotes: 2

Related Questions