Home > Back-end >  Check if multiple elements are in a list
Check if multiple elements are in a list

Time:12-28

i have 2 lists :

A = ['1', '2', '3', '4', '5']
B = ['0', '1', '9', '3', '0']

and i want to check if elements in list B are in A and return a list, if so it should return the same number, if not it should return empty string '', here is the result i'm looking for :

C = ['', '1', '', '3', '']

i Tried using for loop and append result to an empty list, but i got this :

C = ['', '1', '', '', '', '', '', '', '3', ''...]

it doubled the number of elements in the list cuz it looks for the first number in the entire list then move to second one, which makes sense since i'm using for loop, what should i use instead to get back a 5 elements list please ?

thanks in advance.

CodePudding user response:

To get the result you want, you can use a list comprehension to check if each element in B is in A, and then return either the element or an empty string depending on whether it is in A or not.

A = ['1', '2', '3', '4', '5']
B = ['0', '1', '9', '3', '0']
C = [b if b in A else '' for b in B]
print(C)

this will be the output:

['', '1', '', '3', '']

CodePudding user response:

To get your required output, you can just loop through B and check if the item exists in A. If it does, then append it in c otherwise append an empty string to c.

A = ['1', '2', '3', '4', '5']
B = ['0', '1', '9', '3', '0']

c = []
for i in B:
    if i in A:
        c.append(i)
    else:
        c.append('')

print(c)

The output of the above code

['', '1', '', '3', '']

  • Related