Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Build an Application Multidimensional Musical Groups

use remove in for loops

lately i was searching some exercices about lists to practise and i found this exercise: Take two lists, say for example these two:

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]

and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.>> so I tried this way : 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]; c=a; for element in a:; if element not in b :; c.remove(element); print(c) ; but it didn't give me the right answer it gives me this : [1, 1, 2, 3, 5, 8, 13, 34, 89]; can someone help me to understand please ??

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Aymane, you can use the intersection method of a set object.

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]

# to access the intersection method
# you have to convert "a" to a set
common = set(a).intersection(b)

print(common)

The intersection method will return a SET of numbers that both elements have in common. If you need to return a list, you can convert a set to a list using a list() method. I am not shure how efficient this code is (I am a python beginner myself). Let me know what you think ...