0

I'm not sure why I get an error saying index out of range when I test this function. Can anyone please help me fix this?

def intersect_lists(L1, L2): '''(list, list) -> list Return L1 with items not in L2 removed. >>> intersect_lists([1, 2, 3, 4, 5, 6], [4, 2, 6]) [2,4,6] ''' new_list = [] for item in range(len(L1)): if L1[item] == L2[item]: new_list.append(L1[item]) return new_list 
2
  • 1
    Show the full error message. Commented Nov 23, 2017 at 0:07
  • 1
    you use "len(L1)" as range-parameter. You have to substract 1 from that. An array starts at index 0, so [1,2] has the indexes 0 and 1, but the length will be 2 Commented Nov 23, 2017 at 0:22

2 Answers 2

3

Use list comprehension:

def intersect_lists(L1, L2): return [i for i in L1 if i in L2] 

However, your specific error is being caused by the fact that you are iterating over the length of L1, which will ultimately lead to an index error because the length of L1 is greater than L2.

Without list comprehension:

def intersect_lists(L1, L2): final_list = [] for i in L1: if i in L2: final_list.append(i) return final_list 
Sign up to request clarification or add additional context in comments.

1 Comment

How can I do it without list comprehension?
1

Or Boolean And:

list(set(L1) & set(L2)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.