Volume069
Volume069

Reputation: 63

Remove every nth element from the list, if the element is not equal to an element in an other list?

I have two lists of strings:

l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

I need to remove every 2nd element from the l1 if element is not equal to one of the elements from list l2.

so far I have tried:

for e1 in l1:
    i=0
    for e2 in l2:
        if e1!=e2:
            l1.remove(l1[i])
            i=i+1

Expected output:

l1 = ['a1', 'a3', 'a4, 'a5']

How can it be done correctly?

Upvotes: 0

Views: 151

Answers (4)

Georgios Livanos
Georgios Livanos

Reputation: 536

Another simple solution is finding the indexes that are valid for the conditions and then pop the items in reverse order, in order to not mess up indexes.

l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

idx_lst = []
for i in range(len(l1)):
    if (i + 1) % 2 == 0 and l1[i] not in l2:
        idx_lst.append(i)

for idx in sorted(idx_lst, reverse=True):
    l1.pop(idx)

print(l1)

Upvotes: 0

user15801675
user15801675

Reputation:

You can try this:

l1 = ['a1', 'a2', 'a3', 'a4','a5', 'a6']
l2 = ['a3', 'a4']
new_l=[j for i,j in enumerate(l1) if i%2==0 or j in l2]
print(new_l)

Upvotes: 0

It_is_Chris
It_is_Chris

Reputation: 14093

use l1[1::2] to filter the list down to every second value

l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']

for elm in l1[1::2]:
    if elm not in l2:
        l1.remove(elm)

# ['a1', 'a3', 'a4', 'a5']

Upvotes: 0

quamrana
quamrana

Reputation: 39354

You can make a list comprehension to re-create l1:

l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']
l2s = set(l2)

l1 = [item for index,item in enumerate(l1) if (index & 1) == 0 or item in l2s]
print(l1)

Output as requested

I created l2s to make the item in l2s faster if your real l2 is very large.

Upvotes: 3

Related Questions