Is there a method to group the arguments together in Python

Question:

This program I created asks the user for three values, and tells the user if he entered 1, 2 or 3 unique strings. But I feel it looks very repetitive:

def num_unique(v1, v2, v3):
    vlist = []
    if v1 not in vlist:
        vlist.append(v1)
    if v2 not in vlist:
        vlist.append(v2)
    if v3 not in vlist:
        vlist.append(v3)
    return len(vlist)

How can I group the arguments together and loop through them rather than listing them out 1 by 1?

Grateful for all the help, thanks!

Asked By: yijiyap

||

Answers:

You can use set:

def num_unique(v1, v2, v3):
    return len(set((v1, v2, v3)))

print(num_unique(1,2,3)) # 3
print(num_unique(1,1,3)) # 2

You can reduce repetition (of typing v1, v2, v3) further by *args, which also adds flexibility:

def num_unique(*nums):
    return len(set(nums))

print(num_unique(1,2,3)) # 3
print(num_unique(1,1,3,3)) # 2
Answered By: j1-lee

Lets say

prompt = "Enter a string: "
unique_strings = set([input(prompt) for i in range(3)])
print(len(unique_strings))

Not in a form of a function, but fine:D

About the use of set

Answered By: luma
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.