bigd
bigd

Reputation: 69

Removing objects from lists

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

Upvotes: 0

Views: 64

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

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

Upvotes: 3

Serg Anuke
Serg Anuke

Reputation: 168

Or Boolean And:

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

Upvotes: 1

Related Questions