I'm trying to create a list that stores user input to be later manipulated. However when the User inputs names into the temporary list, it updates showing that the nameList has been updated, but when i add the nameList to the concernList, it does not add anything but an empty List! Empty List
concernList = []
nameList = []
def nameLoop():
global concernList
global nameList
first = input("First Name: ")
nameList.append(first)
print(nameList)
middle = input("Middle Initial: ")
nameList.append(middle)
print(nameList)
last = input("Last Name: ")
nameList.append(last)
print(nameList)
concernList.append(nameList)
nameList.clear()
def siteMonitor():
pass
nameLoop()
while True:
newConcernInput = input("Add Another Concern? (y/n)")
if (newConcernInput.lower() == 'y'):
nameLoop()
print("Type 'q' to stop adding concerns. ")
if (newConcernInput.lower() == 'n'):
monitorInput = input("Begin Background Monitoring? (y/n)")
if (monitorInput == 'y'):
siteMonitor()
else:
pass
if (newConcernInput.lower() == 'q'):
break
for count in range(0, len(nameList)):
pass
print(concernList)
print("Added To Concern List.")
CodePudding user response:
concernList.append(nameList)
doesn't create a second list - the newly added element is just a reference to the original list (related). This means that nameList.clear()
will delete the contents of the same list that you just appended to concernList
.
However, I don't see the need for a global nameList
in the first place. This is how I would rewrite the code:
concernList = []
nameList = []
def nameLoop():
first = input("First Name: ")
middle = input("Middle Initial: ")
last = input("Last Name: ")
return [first, middle, last]
def siteMonitor():
pass
nameList = nameLoop()
concernList.append(nameList)
while True:
newConcernInput = input("Add Another Concern? (y/n)")
if newConcernInput.lower() == 'y':
nameList = nameLoop()
concernList.append(nameList)
print("Type 'q' to stop adding concerns. ")
if newConcernInput.lower() == 'n':
monitorInput = input("Begin Background Monitoring? (y/n)")
if monitorInput == 'y':
siteMonitor()
else:
pass
if newConcernInput.lower() == 'q':
break
for count in range(0, len(nameList)):
pass
print(concernList)
print("Added To Concern List.")