aunteth
aunteth

Reputation: 29

Basic list checker

I want to create a list, then enter an int, which will then add the int amount of strings to a list,then print it. So far so good:

list = []
number = int(raw_input("Enter a number: "))
while number > 0:
    list.append(str(raw_input("Enter a word: ")))
    number = number - 1    
print list

However, how do I make it a little more advanced so that you cannot add the same string twice to the list?

Upvotes: 2

Views: 90

Answers (3)

Sandeep Sharma
Sandeep Sharma

Reputation: 141

you can do something like this

mylist = []
number = int(raw_input("Enter a number: "))
while number > 0:
    mystring = str(raw_input("Enter a word: "))
    if mystring not in mylist:
        mylist.append(mystring)
        number = number - 1
    else:
        print('Choose different string')
        next
print mylist

and try to avoid build-in function as variable name. Built-in functions are

https://docs.python.org/2/library/functions.html

Upvotes: -1

Padraic Cunningham
Padraic Cunningham

Reputation: 180532

You can keep a set of all the strings seen, only adding a string and if it has not been seen before, you don't need to keep a count variable either, you can loop until len(data) != number:

number = int(raw_input("Enter a number: "))
seen = set()
data = []
while len(data) != number:
    inp = raw_input("Enter a word: ")
    if inp not in seen:
        data.append(inp)   
        seen.add(inp) 

If the order was irrelevant you could just use a set altogether as sets cannot have dupes:

number = int(input("Enter a number: "))   
data = set()
while len(data) != number:
    inp = raw_input("Enter a word: ")
    data.add(inp)

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174844

Check for whether the list already contain the entered string or not before appending. And don't use in-built keywords as variable names.

list_ = []
number = int(raw_input("Enter a number: "))
while number > 0:
    x = raw_input("Enter a word: ")
    if not x in list_:
        list_.append(x)
        number = number - 1    
    else:
        print "Word is already available"
print list_

Upvotes: 2

Related Questions