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 trial

Python

How to check multiple indexes at once?

So say i have a random list. If i want to check if the number at index 0 is either 0, 1, 2, 3, 4, 5, 6, 7 or 8. How would i go about doing that in a smart way? Obviously i could do an or statement for every action like so:

if list1[0] == 1 or list1[0] == 2 or list1[0] == 3 etc..
    print("something")

But surely there is a smart way of doing it?

1 Answer

I think the easiest way is to use a range, and check for inclusion in that, like this:

if list1[0] in range(1, 9):
    print("something")

The above code will check if list[0] is somewhere between 1 and 8, and will print "something" if it is

Yes but the problem is that the list is a variable, that dosens just contain numbers

For this case, the in operator will simply return False in the event that the object you're testing is not an int, so this solution should still work