-3

If I am constantly adding in strings from a user's input. How can I check that once a string has been added into a list, the contents has already been inside?

x = 4
y = 9
repeatList = []
abc = str(x)+str(y)
repeatList.append(abc)
x = 3
y = 2
abc = str(x)+str(y)
repeatList.append(abc)
x = 4
y = 9
abc = str(x)+str(y)
repeatList.append(abc)
print(repeatList)

Gives an output:

['49', '32', '49']

The desired output is ['49','32'] and a message "You have inputted '49' already."

Please note in the actual code we do not assign variables to an int, instead, we allow the player to input and if they've already written it before then we let them know they have typed in the same input and that they still lose a 'move'.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Bucciarati
  • 17
  • 5

3 Answers3

2

Let's assume you want to insert variable x to your list, so you check:

if x in lst:
    print ("You have inputted", x, "already.")
else:
    lst.append(x)
Idos
  • 15,053
  • 14
  • 60
  • 75
0
x = 4
y = 9
repeatList = []
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))

x = 3
y = 2
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
x = 4
y = 9
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
print(repeatList)

Output:

You have inputted 49 already.
['49', '32']
YBathia
  • 894
  • 1
  • 8
  • 18
0

In addition to what @idos already said:
If you are not interested in the order of insertion and the objects you add are hashable, you could use a set, which has faster performance than lists when it comes to check if an element is already inside it.

>>> s = set()
>>> s.add(49)
>>> s
set([49])
>>> s.add(32)
>>> s
set([32, 49])
>>> s.add(49)
>>> s
set([32, 49])
>>> s.add('49')
>>> s
set([32, 49, '49'])
Community
  • 1
  • 1
Alberto Chiusole
  • 2,204
  • 2
  • 16
  • 26