Fam, help me!...i'm new to python and currently trying to write a function that adds values to an empty list. it should return true when i add values and false, if i add a value that already exists in the list.
The issue is when i add a value that already exists, it still prints it out when the function is called instead of given the designated error message. I know something's wrong, i just don't know where exactly.
I'd appreciate your input (pun intended).
This is the code i came up with:
myUniqueList = []
def addToMyUniqueList(x):
if x != myUniqueList:
print("My unique list:")
print(myUniqueList)
else:
print("Error; item already exists!")
addToMyUniqueList(myUniqueList.append(3))
output:
My unique list:
[3]
addToMyUniqueList(myUniqueList.append(3))
output:
My unique list:
[3, 3]
Top comments (6)
On another note, you can use the backtick symbol(`) to create code boxes. You write it three times then your code and end the code section with three more backticks. After the first three backticks, you can also write python(in all lowercase) to get syntax highlighting for python in your post. If you are interested you can press the info-box thing here on Dec to read more about the markdown syntax used 😁
So I think the issue is the use of the not equals operator (!=). It checks if the thing to the left is not equal to the thing on the right. If I understood your example the check if statement with values witten out would be:
Because, the value on the left is a number and the the value to the right is a list containing the value 3 they will never be equal.
Instead python as two other operators in and not in. Which can be used to check if a values exist in a list (or other container supporting it). In this case the is statement would be:
Hope this was helpful, feel free to ask any questions if I was unclear😊
Oh, this was really helpful. I was totally unaware of these other operators. The code works fine now. Thanks again!.
Thanks to @dmitrypolo and @Fredrik Bengtsson for their help. It does what i want now! hurray!! lol.
myUniqueList = []
def addToMyUniqueList(x):
if x not in myUniqueList:
print("New item added:", x)
return myUniqueList.append(x)
else:
print("ERROR!!! Item already exists!")
addToMyUniqueList("salt")
print(myUniqueList)
The function you created also does not return anything, it only prints out information. Your
append
operation should happen when one of the conditions matches.Oh, thanks Dmitry...This was really helpful. To be honest, i didn't quite understand the use of the return(statement), but your input helped me find out more. The code works fine now.