Search code examples
pythonlistfractions

How to make a character in a list appear only once?


ilist1 = [-1, 1, 2, 3, 1]

In the above list, "1" would appear twice. I need the program to only let it appear once in the new list.


Solution

  • Use a set comprehension instead:

    fracs = {str(Fraction(x, y)) for x in ilist1 for y in ilist2}
    

    A set can only hold unique values, so any 1/3 duplicates are removed.

    Note that you are not producing 4 combinations of pairs formed of elements in ilist1 and ilist2. You are producing the product of the two lists, so 4 * 4 = 16 combinations. If you expected to only get 4, you'll need to use the zip() function:

    fracs = {str(Fraction(x, y)) for x, y in zip(ilist1, ilist2)}
    

    Demo:

    >>> from fractions import Fraction
    >>> ilist1 = [-1, 1, 2, 3]
    >>> ilist2 = [-3, 3, 6, 9]
    >>> {str(Fraction(x, y)) for x in ilist1 for y in ilist2}
    set(['1/6', '1/3', '1/2', '-2/3', '1/9', '-1/3', '2/9', '1', '-1', '-1/6', '-1/9', '2/3'])
    >>> {str(Fraction(x, y)) for x, y in zip(ilist1, ilist2)}
    set(['1/3'])