Creating a list from the the intersection of two lists containing unique integers


  • I've been working on beginner python exercises and one exercise required me to take two lists, say for example these two

    a = [1,1,1,2,3,4,5,5]
    b = [1,2,4,6]
    

    and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
    I have written my code and I think that I have a solution to the problem. The problem is that when I look at the solutions I've seen online, it seems like my solution is unique. Not that this is necessarily a bad thing but I'm interested in knowing if I wrote good quality/efficient code. Here is a link to my code. https://onlinegdb.com/rkMQ1lbqL

    a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,8,5,7,9,21,55,89,89,55]
    b = [1,1,2,3,5,8,13,21,34,55,89]
    intersection = []
    for i in a:
            for j in b:
                    if j == i:
                            intersection.append(j)
    intersection_set = set(intersection)
    new_list = list(intersection_set)
    print(new_list)
    

    I'm specifically curious to know if the nested for loop is a bad idea or if there's another concept that I could use that would result in more compact code or reduce computation assuming huge amounts of data were being compiled.





  • https://onlinegdb.com/SyiGwc-5U
    Hey , This is a simple solution to your problem using list comprehensions



  • Woah, this is very compact code. Yes, I've been introduced to list comprehensions but one thing that is incorrect about the code is that it needs to only include unique values. This code prints some numbers repeated times.





  • Thanks! This works and it only takes up 4 lines of code. The computation time is also much faster than my code. I think that I understand why it works faster as well. Your code executes after looping 23 times. However, my code executes after 11 iterations of 23 or 253 iterations which is 11 times more than my code. Also, it took 13.7 milliseconds, whereas as mine took 185 milliseconds which is 13.5 times as fast. I suspect that the method that I used where I changed my list into a set and then returned to transform it into a list also took more time than your method you recommended to me, which could partially explain the discrepancy in computation time as well.