Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – function find list in list

I wrote the function to find list A is in List B, the code as below:

def isinlist(l1,l2):
    flag=1
    for i in range(0,len(l1)+1):
        if l1[i] not in l2:
            flag = 0
    return flag
a1 = ['hello','hi','123']
a2 = ['no worry','hello','hi','123'' ]# f1 = isinlist() 
print(isinlist(a1,a2)) 

it show the error as below

IndexError: list index out of range

I thought the error come from l1 and l2 wasn’t defined range in the function? Can someone help advise on this ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the issue id in the line

for i in range(0,len(l1)+1):

in this loop i will eventually be larger than the length of l1 and thus l1[i] will be out of range

instead use

for i in range(len(l1)):

(range() starts at 0 by default)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading