Please have a look at the following 2 ways of implementation. Please prefer 2nd way. Also check their related o/p that I have pasted from my terminal.
This is just to answer the question, check 2nd way and try to implement like that.
set1 = [1,2,3,4,5,6,7,8]
new_list = []
while True:
# Make sure to give valid input like, 12, 43, -54 etc.
# otherwise to handle the Exception, we will need to use
# try-except statement
user_input = int(input('Insert a number: '))
if not user_input in set1:
new_list.append(user_input)
break
print(new_list)
# Insert a number: 3
# Insert a number: 6
# Insert a number: 7
# Insert a number: 8
# Insert a number: 9
# [9]
Always try to implement your logic using modular programming / OOP, that makes your code re-usable and efficient for further use.
def get_new_list(set1, no_of_new_items):
new_list = []
# Adding no_of_new_items(integers) in new_list
for i in range(no_of_new_items):
additional_string = ''
while True:
# Make sure to give valid input like, 12, 43, -54 etc.
# otherwise to handle the Exception, we will need to use
# try-except statement
user_input = int(input(('(%d) Insert a number ' + additional_string + ": ") % (i + 1) ))
if not user_input in set1:
new_list.append(user_input)
break
else:
additional_string = "(other than %d, it's already in other list)" % (user_input)
print('Pass no. %d is over, new_list: %s\n' % (i+1, new_list))
return new_list
if __name__ == "__main__":
set1 = [1,2,3,4,5,6,7,8]
new_list = get_new_list(set1, 5)
print("New list: ", new_list)
# (1) Insert a number : 9
# Pass no. 1 is over, new_list: [9]
# (2) Insert a number : 5
# (2) Insert a number (other than 5, it's already in other list): 6
# (2) Insert a number (other than 6, it's already in other list): 7
# (2) Insert a number (other than 7, it's already in other list): 8
# (2) Insert a number (other than 8, it's already in other list): 10
# Pass no. 2 is over, new_list: [9, 10]
# (3) Insert a number : 89
# Pass no. 3 is over, new_list: [9, 10, 89]
# (4) Insert a number : 90
# Pass no. 4 is over, new_list: [9, 10, 89, 90]
# (5) Insert a number : 3
# (5) Insert a number (other than 3, it's already in other list): 2
# (5) Insert a number (other than 2, it's already in other list): 2
# (5) Insert a number (other than 2, it's already in other list): 4
# (5) Insert a number (other than 4, it's already in other list): 7
# (5) Insert a number (other than 7, it's already in other list): 67
# Pass no. 5 is over, new_list: [9, 10, 89, 90, 67]
# New list: [9, 10, 89, 90, 67]