You can use simple list comprehension like this,
same_fruits = [frt for frt in fruit if frt in fruit1]
You can as well use data structure in Python known as set
, If you are aware of set
, it allows you to get intersection.
fruit = set(['apple', 'pear', 'peach', 'orange'])
fruit1 = set(['pear', 'orange', 'banana', 'grapes'])
same_fruits = fruit.intersection(fruit1)
Update (Problem in your code)
Your code does not work because, str
type itself is a iterable
in Python. So, when you use +
operator with list
and apple
or orange
, which is again a utterable
, Python tries to extend
instead of using append
method. You could also make a small change in your code, to make sure that str
is appended as a whole instead of treating it as individual components by exclusively using append
method. Instead of +
operator which in this case is extending iterable
with another iterable
, use append
method.
fruit = ['apple', 'pear', 'peach', 'orange']
fruit1 = ['pear', 'orange', 'banana', 'grapes']
same = []
for f in fruit:
for ff in fruit1:
if f == ff:
same.append(f)
print(same)