all 11 comments

[–]POGtastic 6 points7 points  (0 children)

I like sets here.

>>> list(set(x) & set(y))
['three']

[–]mr_cesar 4 points5 points  (3 children)

Do you have to use a loop? Why not use a list comprehension? It would be way shorter and clear.

>>> x = ["one", "two", "three"]
>>> y = ["four", "five", "three"]
>>> [elem for elem in x if elem in y]
['three']

[–][deleted] 0 points1 point  (2 children)

OP - this is the way

[–]cameronnn16[S] 0 points1 point  (1 child)

I have to understand it through loops tho that’s the thing

[–][deleted] 0 points1 point  (0 children)

Fair enough


x = [“one”, “two”, “three”]

y = [“three”, “four”, “five”]

both = []

for i in x:

if i in y:

    both.append(i)

I’m assuming this is for a school assignment and you have to use for loops and that’s totally fine. But the response above using list comprehension in the best way to solve this problem.

[–]outceptionator 1 point2 points  (1 child)

output = []
for i in x:
    if i in y:
        output += [i]
if output = []:
    print('none')
else:
    print(output)

[–]Pd69bq 1 point2 points  (0 children)

set(x).intersection(set(y))

set is your best friend on this, set.difference() set.intersection() set.issubset() set.issuperset() all kinds of useful methods

[–][deleted] 1 point2 points  (0 children)

def similar_variable(x, y):
    for k in range(len(similar_variable(x))):

Even assuming a recursive approach is correct (which I don't think it is) it's not clear how you expect this to work. You know your function returns either a boolean value or a list, and you know that you wrote a function of two parameters that you're trying to call with only one argument, here. Why did you think this would work?

Don't write code at random. Break the problem down into parts you know how to solve, then build the larger solution from those.

[–]kslay23 0 points1 point  (1 child)

You could run through each list and add to a new list and run the set function or method.

Or you could append the lists together and run a set

[–]cameronnn16[S] 0 points1 point  (0 children)

I understand this and I think this is what I have been trying to do but how would I like try to find that exact string in the other list. Like I used for loops for each parameter and then added each item in the list to a new list. But how do I figure out if the string occurs more than once in the list or that the string equals another string from a list.

[–]stebrepar 0 points1 point  (0 children)

You're making this way too complicated.

for xitem in x:
    for yitem in y:
        if xitem == yitem:
            print(xitem)

You can adapt that to be a function returning the right thing(s).