user7119314
user7119314

Reputation:

duplicate returns more numbers than required

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]

if len(set(a)) > len(set(b)):  # finds the biggest list
    largest = a
    smallest = b
else:
    largest = b
    smallest = a

common = largest

for i in largest:
    if i not in smallest:
        common.remove(i)

print(common)

prints: [1, 2, 3, 5, 7, 8, 10, 12, 13] 7, 9, 10, 11, 12 shouldnt be in the list. because they aint in the smaller list.

What am i doing wrong?

Upvotes: 0

Views: 44

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22564

Your line common = largest does not copy the values of list largest into a new list common. It rather makes it so both those variables are pointers to the same list. So when you loop over largest and remove from common you are modifying the list you are looping over. That is a bad idea.

Make a real copy with

common = largest[:]

or

common = list(largest)

However, a much more pythonic way to get a good list of the elements in both lists is just the single line

common = sorted(set(a) & set(b))

Note that this returns the list in sorted order, which may be different from the original order.

Upvotes: 2

paisanco
paisanco

Reputation: 4164

Your code relies on the assumption that statements like

largest=a

copy the list a to largest. This is not true in Python. Rather that statement just makes largest a reference to the old list a.

Your code, to copy lists properly, should look like this:

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]

if len(set(a)) > len(set(b)):  # finds the biggest list
    largest = list(a)
    smallest = list(b)
else:
    largest = list(b)
    smallest = list(a)

common = list(largest)

for i in largest:
    if i not in smallest:
        common.remove(i)

print(common)

You will then get the result

[1, 2, 3, 5, 8, 13]

Upvotes: 2

Related Questions