Reputation:
My list comprehension returns the error "List index out of range" if the value does not exist in the list.
Objective: Check a three-letter code for a country given by a variable (country) and transform the code into a two-letter code by looking up a list of tuples (COUNTRIES)
Constant:
# Two letter code, three letter code, full name
COUNTRIES = [
('US', 'USA', 'United States'),
('DE', 'DEU', 'Germany'),
....
]
Code:
country = 'EUR'
# Check if code in country has 3 characters (I have multiple checks for two letter codes too) and is not None
if len(country) == 3 and country is not None:
country = [code2 for code2, code3, name in COUNTRIES if code3 == country][0]
If I only include a list with three letter codes USA and DEU, the code works fine. If I add the fictitious code "EUR", which is not a valid country code in the variable "country", than I get the List index out of range error.
How can I return None instead of breaking the program? The variable country will be used later on again.
Upvotes: 0
Views: 1195
Reputation: 3307
I don't think List comprehensions are a good choice here. They are good when you want to turn one list into another list, which you don't really want to do here. A better approach would be a regular for loop with a return
here.
However, my personal approach would be to transform the list lookups into dict lookups instead:
COUNTRIES_LUT = {}
for code2, code3, country in COUNTRIES:
COUNTRIES_LUT[code2] = country
COUNTRIES_LUT[code3] = country
At the end of that, you can just use COUNTRIES_LUT[your_str]
as expected.
If you generate this lookuptable at the start, this also has the bonus of being faster, since you don't need to loop through every element of the list every time.
Upvotes: 1