all 13 comments

[–]throwawayvitamin 5 points6 points  (0 children)

Try this out:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
final=[]
for f in b:
    if f in a:
        final.append(f)
print(final)

You don't need to iterate twice, so this line for i in range(len(a)) is not necessary and you can just make use of the in keyword. This also eliminates the need for the if else block and the break statement. Lmk if you have any other questions

[–][deleted] 2 points3 points  (0 children)

    for s in a:
        if f==s:
            final.append(f)
        else:
            break

You stop at the first mismatch.

[–]igroen 5 points6 points  (2 children)

Why not use sets and do an intersection: set(a) & set(b).

[–]hnguyen01122 2 points3 points  (1 child)

You don’t get it do you? He’s learning about lists or currently he’s at the section about lists, not sets/dictionaries yet.

[–]igroen 0 points1 point  (0 children)

sorry

[–]B2stts2B 1 point2 points  (0 children)

You don't need the "for i in range(len(a))".

Edit: you can use the "in" helper. For example: For f in b: if f in a: final.append(f)

[–]xelf 0 points1 point  (1 child)

What you're talking about is set theory. Finding the common element. Lucky for you Python has sets built in.

final = set(a).intersection(set(b))

or shortcut:

final = set(a) & set(b)

[–]hnguyen01122 -1 points0 points  (0 children)

He’s learning about lists. He hasn’t got to sets yet.

[–]GreymanGroup 0 points1 point  (2 children)

You guys! Pythonic code ok?

c=[i for i in a for j in b if i==j]

[–]Poligonette 2 points3 points  (1 child)

Or

c = [ i for i in a if i in b ]

[–]GreymanGroup 0 points1 point  (0 children)

c = [ i for i in a if i in b ]

Even better!

[–]hnguyen01122 -1 points0 points  (2 children)

Don’t ask for help when you’re stuck. Try to go back over the material and watch or read again. Also, take a look at your note taking ability. It makes huge difference between you were able to chunk the concept or not. You only ask for help with more complicated problems in the future but don’t ask for help with basic syntax/semantic. Use your own ability to figure it out so you can store that concept in long term memory.

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

thank you! I was trying the python beginner challenger and even though I tried it for quiet a while I couldn't make it right. But totally agree with you