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

Question:

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,"

Asked By: crtnnn

||

Answers:

Replace:

    for u in unique_values:
        print(u, end=", ")

with the pythonic:

    print(', '.join(unique_values))

Also generally better style to

return unique_values

and use

print(', '.join(unique(wells)))

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

Added in Edit: the following solution works also for non-string lists.

''' Print unique values in a list or numpy array '''

x = [1, 2, 2, 5, 7, 1, 3]
print(x)

# set(x) will return a set of the unique values of x
u = set(x)
print(u)

# remove the curly brackets
str_u = str(u).strip("}{")
print(str_u)

and the result is

1, 2, 3, 5, 7
Answered By: Triceratops

hope the below changes helps you 🙂

def unique(list1):
    unique_values = []
    for u in list1:
        if u not in unique_values:
            unique_values.append(u)
    return unique_values


wells = ["U1", "U1", "U3", "U3", "U3", "U5", "U5", "U5", "U7", "U7", "U7", "U7", "U7", "U8", "U8"]
req = unique(wells)
# prints in list format
print(f"The unique values from list are...: {req}")
# prints in string format
print(f"The unique values from list are...: {' '.join(req)}")

or the unique values can also be found out using set(wells)

Answered By: Harishma Ashok

There are a couple issues here: the trailing , as noted in the question, testing membership on an unsorted list. Use str.join() to handle the trailing comma, and don’t even try to keep track of unique values and check if a new value has already been seen, just cast to set.

def unique(list1):
    unique_values = set(list1)
    print(', '.join(sorted(unique_values)))


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)
Answered By: Michael Ruth
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.