Python "or" when one of the vars may not exist?

Suppose something like this:

if mylist[0] == 1 or mylist[12] == 2: # do something 

But I'm not sure that mylist[12] will always be out of range. What to do to keep things simple and still check if an index exists? I would not like to do

 if mylist[0] == 1: # do something elif mylist[12] == 2: # do the EXACT same thing 

As you get too many identical lines of code.

+4
source share
4 answers

You can check the length of the list:

 if mylist[0] == 1 or (len(mylist) > 12 and mylist[12] == 2): 

A short distribution of and used here to ensure that mylist[12] will not be evaluated if the list has 12 elements or less.

+10
source

A string always returns a value (even if it is an empty list). You can do:

 if myList[0] == 1 or myList[12:13] == [2]: 
+4
source

Or, if you think this is more readable, for example:

 if mylist[0] == 1: # do something elif len(mylist) > 12 and mylist[12] == 2: # do same thing 
+1
source
 def get(arr, ind, default=None): try: return arr[ind] except IndexError: return default if get(myList, 0)==1 or get(myList, 12)==2: # do something 
0
source

Source: https://habr.com/ru/post/1413344/


All Articles