epa la arepa
epa la arepa

Reputation: 3

How to convert this to a list comprehension

I want to convert this part of the code to a list comprehension, however my knowledge of this method is still very weak and it does not occur to me how, if you could help me, I would appreciate it.

list_1 = ["h",'i',' ', 'w','o','r','l','d'] 
list_2 = ["h",'i',' ', 'm','o','o','n']   

list_3 = []

for word in list_1:
    if word in list_2 and word not in list_3:
        list_3.append(word)

print(list_3)

Upvotes: 0

Views: 159

Answers (4)

Rado Cisar
Rado Cisar

Reputation: 21

Here you go:

[list_3.append(w) for w in list_1 if (w in list_2) and (w not in list_3)]
list_3

Output:

['h', 'i', ' ', 'o']

Enjoy!

Upvotes: 2

balderman
balderman

Reputation: 23825

The right way to do it is using set data structure.

list_1 = ["h",'i',' ', 'w','o','r','l','d'] 
list_2 = ["h",'i',' ', 'm','o','o','n'] 
set_1 = set(list_1)
set_2 = set(list_2)
set_3 = set_1 & set_2
print(set_3)

output

{' ', 'o', 'i', 'h'}

Upvotes: 1

wjandrea
wjandrea

Reputation: 33169

In this case, this works:

list_3 = [word for word in list_1 if word in list_2]
print(list_3)  # -> ['h', 'i', ' ', 'o']

If you want to keep excluding duplicates in list_3 then it gets a bit more complicated. Check out Removing duplicates in lists. For example, this will work in Python 3.7+:

dict_3 = {word: None for word in list_1 if word in list_2}
print(list(dict_3))  # -> ['h', 'i', ' ', 'o']

Upvotes: 1

Alex Liu 33214
Alex Liu 33214

Reputation: 72

This is all you need

next time please do more reaserach

list_1 = ["h",'i',' ', 'w','o','r','l','d'] 
list_2 = ["h",'i',' ', 'm','o','o','n','']   

list_3 = []

for i in range(0, len(list_1)):
    if list_1[i] != list_2[i]
        list_3.append(list_1[i])

print(list_3)

result:

['m','o','n']

Upvotes: -1

Related Questions