i have two lists here. What should i do to display the all common friends and not only one of them(With an explanation for it)? Thanks!
def common_friend(Name1, Name2):
for i in Name1 and Name2:
common_friend = i
if common_friend in Name1 and Name2:
print(f"The common friend is: {common_friend}")
Nico = ["Nicole", "Mo", "Jani", "Maik", "Lena"]
Younes = ["Johannas", "Sara", "Basem","Lena", "Philip", "Mo"]
common_friend(Nico, Younes)
CodePudding user response:
What you describe sounds like set intersection; I would turn the lists into sets and use the intersection operator:
>>> Nico = {"Nicole", "Mo", "Jani", "Maik", "Lena"}
>>> Younes = {"Johannas", "Sara", "Basem","Lena", "Philip", "Mo"}
>>> Nico & Younes
{'Mo', 'Lena'}
Mo and Lena are the common friends of Nico and Younes.
Sets are described in the tutorial as well as in the reference; both also show how you can convert existing lists (actually, any iterable) to sets.
CodePudding user response:
def common_friend(friend_1, friend_2):
common_friends = []
for name_1 in friend_1:
if name_1 in friend_2:
common_friends.append(name_1)
return common_friends
Nico = ["Nicole", "Mo", "Jani", "Maik", "Lena"]
Younes = ["Johannas", "Sara", "Basem", "Lena", "Philip", "Mo"]
common_friends = common_friend(Nico, Younes)
print(common_friends) # ['Mo', 'Lena']
CodePudding user response:
If you like or should stick with interating over the list of names, changing your code to the following should solve your question.
def common_friend(Name1, Name2):
# iterate over all names in `Name1` e.g. friends of Nico
# as the common friends needs to be in both lists,
# we can just iterate over one of them to check for common friends
for name in Name1:
# check if the name is in the list of `Name2`, e.g. the friends of Younes
# as we iterate over alle Names in `Name1` we do not need to check for `if name in Name1`
if name in Name2:
print(f"The common friend is: {name}")
Nico = ["Nicole", "Mo", "Jani", "Maik", "Lena"]
Younes = ["Johannas", "Sara", "Basem","Lena", "Philip", "Mo"]
common_friend(Nico, Younes)
CodePudding user response:
The simplest solution would be to iterate over both list and find duplicates:
for nicos_friend in Nico:
for younes_friend in Younes:
if nicos_friend == younes_friend:
print(f'Same friend {nicos_friend}')
or simplier:
for nicos_friend in Nico:
if nicos_friend in Younes:
print(f'Same friend {nicos_friend}')
CodePudding user response:
You can use the intersection
of sets
for that:
Nico = ["Nicole", "Mo", "Jani", "Maik", "Lena"]
Younes = ["Johannas", "Sara", "Basem","Lena", "Philip", "Mo"]
list(set(Nico).intersection(set(Younes)))
Output:
['Lena', 'Mo']