Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List Overlap
#1
I'm doing online problems to get me back into python after not touching it for a couple of years.

Problem comes from http://www.practicepython.org/exercise/2...erlap.html

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.

Extras:

Randomly generate two lists to test this
Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)

This is my attempt but it doesn't work:

def exc5():
    a = random.sample(range(20), 10)
    b = random.sample(range(20), 10)
    c = [i for i in a if a in b]
    print(a)
    print(b)
    print(c)


exc5()
Sample output:

Output:
[9, 17, 6, 4, 12, 16, 18, 5, 1, 7] [4, 5, 19, 12, 9, 18, 14, 2, 8, 11] []
As you can see the numbers which are in both lists should be in the third list but it's an empty list.

I am aware you can do this with sets but I'm interested as to why this doesn't work.

Huh
Reply


Messages In This Thread
List Overlap - by Josh_Python890 - Jun-12-2019, 12:00 AM
RE: List Overlap - by micseydel - Jun-12-2019, 12:51 AM
RE: List Overlap - by perfringo - Jun-12-2019, 01:59 AM
RE: List Overlap - by micseydel - Jun-12-2019, 02:47 AM
RE: List Overlap - by kotter - Jun-12-2019, 03:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Overlap Trouble erfanakbari1 1 2,064 Mar-18-2019, 02:36 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020