Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFernando Mendoza
345 PointsOk so if i use the in statement i can create a not in statement and not have to use an else statement for the in state
color = 'yellow'
colors_available = ['Green', 'Blue', 'Red', 'Black']
if color in colors_available:
print('Nice color choice buddy')
# Here don't use else statement but then use if not statement
if color not in colors_available:
print('Choose a better color choice buddy')
# Are those two statements the same as writing
if color in colors_available:
print('Nice color choice buddy')
else:
print('Choose a better color choice buddy')
1 Answer
Michael Hulet
47,913 PointsYes, they're equivalent. The not
operator just takes a boolean and inverts it. If it sees false
, it give back true
, but if it sees true
, it gives back false
. So yeah, those methods are equivalent, but the second method is preferred because it creates a clear logical link between the 2 block of code, and it means you don't have to go through all the operations of checking array inclusion for a second time, which can be a computationally expensive thing to do