Srinivasan
Srinivasan

Reputation: 12050

Create a unique list

I have written below python program to get unique list. But i want to reduce this code for same output. since python does not have break/continue outer loop, i could not reduce this count. could you please help how to reduce in some way.

empty_list=list()
length=int(input("enter the unique element length: "))
number=int(input("enter the element:"))

empty_list.append(number)
x=1 

while(x<length):
    z=0
    a=int(input("Enter the element:"))

    for y in empty_list:
        if(y==a):
            z=1

    if z==0:
        empty_list.append(a)
        x+=1 
    else:
        x=x

print(empty_list)

Upvotes: 0

Views: 126

Answers (2)

user783836
user783836

Reputation: 3529

Instead of a list use a set set. You don't need to check for uniqueness and can just create a list from the set at the end.

length=int(input("enter the unique element length: "))
number=int(input("enter the element:"))

number_set = set()
x=1 

while(x<length):
    z=0
    a=int(input("Enter the element:"))

    number_set.add(a)
    x = x + 1

print(list(number_set))

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

unique = list()
length = int(input("enter the unique element length: "))

while len(unique) < length:
    number = int(input("Enter the element:"))
    if number not in unique:
        unique.append(number)

print(unique)

Upvotes: 2

Related Questions