Python Forum
Exercise List Overlap - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Exercise List Overlap (/thread-33137.html)



Exercise List Overlap - Damian - Apr-01-2021

Hi all,

I've got an exercise and I'm trying to solve it.

I'm a Python beginner.

EXERCISE
Take two lists (you can use the ones in the example below) and write a program that prints a list that contains only the elements of the two lists that are equal and in the same position without duplication.
e.g.,
a = [5, 3, 5, 44, 4, 55, 4]
b = [5, 4, 55, 4, 4, 55, 4, 55, 9, 10, 11]


So, this is what I've done:

a = [5, 3, 5, 44, 4, 55, 4]
b = [5, 4, 55, 4, 4, 55, 4, 55, 9, 10, 11]

list_of_tuples = list(zip(a, b))
result = []
for tuple in list_of_tuples:
if tuple[0] == tuple[1]:
result.append(tuple[0])

print(result)
# [5, 4, 55, 4]

Then I've to keep the list order and skip duplicates.

What do you suggest me to do?
Do you think there's a better way of solving the problem from the beginning? (from the point of view of a beginner of course)


RE: Exercise List Overlap - Damian - Apr-01-2021

If I use a set:

print(list(set(result)))

I get [4, 5, 55]

I don't understand why Python re-arrange the list when I create a set...


The result should be [5, 4, 55] because the order matters


RE: Exercise List Overlap - bowlofred - Apr-01-2021

sets don't keep track of the order that things were added. If you care about the order, you need something other than a set. They're great for removing duplicates, which is not useful here.

This exercise looks like a good use for zip(). It takes in two streams and combines them, keeping the order. That's exactly what is needed here.


RE: Exercise List Overlap - Damian - Apr-01-2021

Thank you for your swift reply


RE: Exercise List Overlap - ICanIBB - Apr-01-2021

Dance Dance Dance


RE: Exercise List Overlap - Damian - Apr-01-2021

So, to finish off I can write something like this:

without_duplicates = []
for element in result:
   if element not in without_duplicates:
       without_duplicates.append(element)

print(without_duplicates)
Is there an easier way to solve it?

Thank you all


RE: Exercise List Overlap - bowlofred - Apr-01-2021

Bah, I missed the "without duplicates" on the original problem. Sorry for the confusion.

You can use the set to remove duplicates, but then you'd have to refer back to the original list for the order.

But with Python 3.6 (I think), dicts not only remove duplicates but also keep order. So you can shove them into a dict and then pull the keys out.

>>> l
[5, 4, 55, 4]
>>> list(dict.fromkeys(l))
[5, 4, 55]



RE: Exercise List Overlap - Damian - Apr-02-2021

Wowww, this is cool!

This is a nice suggestion :) Thank you all