Create a global variable called myUniqueList
. It should be an empty list to start.
Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList
, unless its value already exists in myUniqueList
. If the value doesn't exist already, it should be added and the function should return True
. If the value does exist, it should not be added, and the function should return False
;
extra is if we can make the remaining values to a list called my leftovers
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
return True
else:
myLeftovers.append(newElement)
return False
print(addUniqueElement())
Something to note is that your attempt was very good. It did everything right except for a few things:
You should print out the list if you want to see the final list eg.
print(myUniqueList)
Next, the function requires an argument, in this case, I'll use "cool" so now we have
addUniqueElement("cool")
print(myUniqueList)
In the end we get
myUniqueList = []
myLeftovers = []
def addUniqueElement(b):
if b not in myUniqueList:
print(myUniqueList.append(b))
else:
myLeftovers.append(newElement)
addUniqueElement("cool")
print(myUniqueList)
print(myLeftovers)
There's no point in printing when you call myUniqueList.append(b)
. It just updates the list, it doesn't return anything.
You need to pass an argument when you call the function.
newElement
should be b
.
def addUniqueElement(b):
if b not in myUniqueList:
myUniqueList.append(b)
return True
else:
myLeftovers.append(b)
return False
print(addUniqueElement(1)) # True
print(addUniqueElement(2)) # True
print(addUniqueElement(1)) # False
print(addUniqueElement(5)) # True
print(addUniqueElement(10))# True
print(addUniqueElement(5)) # False
print(myUniqueList) # [1, 2, 5, 10]
print(myLeftovers) # [1, 5]
here you can continuously add text (ex numbers ) and watch them being added to the one or to the other list
myUniqueList = []
myLeftovers = []
def addUniqueElement(text):
if text not in myUniqueList:
myUniqueList.append(text)
return True
else:
myLeftovers.append(text)
return False
while ( 1 ):
text = input("text: ")
addUniqueElement(text)
print("myUniqueList: ", myUniqueList)
print("myLeftovers: ", myLeftovers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.