0

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81

4 Answers4

2

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!

Rado Cisar
  • 21
  • 4
  • This works, but the style is bad. [Don't use comprehensions for side effects](https://stackoverflow.com/q/5753597/4518341), and [don't use bitwise operators when you should use logical operators](https://stackoverflow.com/q/3845018/4518341). – wjandrea Mar 22 '20 at 20:43
  • @wjandrea yes, my method may be a bit computationally expensive, but it solves the example given. Unless you have a complex code for a large program, this should not be a problem. for the bitwise vs boolean operators, you are right the boolean `and` makes more sense here. – Rado Cisar Mar 24 '20 at 10:22
1

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']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

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'}
balderman
  • 22,927
  • 7
  • 34
  • 52
-1

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']