Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get rid of comma at the end of printing from loop

So basically I have the list of many points and I want to extract only unique values.
I have written a function but I have 1 problem: how to avoid printing comma at the end of the list?

def unique(list1):
    unique_values = []
    for u in list1:
        if u not in unique_values:
            unique_values.append(u)
    for u in unique_values:
        print(u, end=", ")


wells = ["U1", "U1", "U3", "U3", "U3", "U5", "U5", "U5", "U7", "U7", "U7", "U7", "U7", "U8", "U8"]
print("The unique values from list are...:", end=" ")
unique(wells)

my output is for now: "The unique values from list are…: U1, U3, U5, U7, U8,"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It might be an overkill but you can use NumPy "unique" method, which is probably more efficient, a specially for large arrays or long lists.

The following code will do:

import numpy as np
x = np.array(['a', 'a', 'b', 'c', 'd', 'd'])
y = np.unique(x)
print(', '.join(y))

and the result is:

a, b, c, d
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading