List conditionals
in
operator
In previous section we wrote a complex condition which checked if the value of country
is Cameroon or Malaysia. But what if we have a list of countries? Actually here's a full list of countries with voting age of 21
:
['Cameroon', 'Malaysia', 'Oman',
'Samoa', 'Singapore', 'Tokelau',
'Tonga']
We could persue our previous approach and write a complex condition using or
operator. That would require us to write a lot of code. But there's a better way. We can use the in
operator to check if a value is in a list. Our program would look like this in such case:
age = 20
country = 'Singapore'
countries_21 = ['Cameroon', 'Malaysia', 'Oman',
'Samoa', 'Singapore', 'Tokelau',
'Tonga']
if age < 21 and country in countries_21:
print(f'In {country}, you must be 21 to vote')
else:
print('You are eligible to vote!')
which produces:
In Singapore, you must be 21 to vote
not in
operator
We can also check if a value is not in a list using not in
operator. Here's an example:
awesome_cars = ['BMW', 'Porsche']
expensive_cars = ['Mercedes', 'Rolls Royce']
fast_cars = ['Ferrari', 'Bugatti']
car = 'Toyota'
not_awesome = car not in awesome_cars
not_expensive = car not in expensive_cars
not_fast = car not in fast_cars
if not_awesome and not_expensive and not_fast:
print('This car is boring!')
which indeed tells us:
This car is boring!
Check if list is empty
If we want to check if a list is empty we can use the fact that empty lists are considered False
in Python. Here's an example:
cars = []
if cars:
print(f'You have {len(cars)} cars!')
else:
print('You have no cars!')
This produces:
You have no cars!
If you add few more cars to the list
cars = ['BMW', 'Porsche']
the output will change to:
You have 2 cars!