Reputation: 21
is it possible to detect identical objects as different variables, say object1=(1,2,3) and object2=(1,2,3).
list = []
If i now put object 1 in the list together with object 2 the list becomes:
list.append(object1)
list.append(object1)
print(list)
list = [(1,2,3),(1,2,3)]
How can i let python decide whether or not the first element in the list is object1? This is something i have to do for my school project.
Upvotes: 1
Views: 550
Reputation: 21
I found it.
You can do this with the is
function.
Block1 is Block2
list[0] is list[1]
response: False
Upvotes: 0
Reputation: 17322
you could cast to set then back to list:
my_list = [(1,2,3),(1,2,3)]
print(list(set(my_list)))
# [(1, 2, 3)]
or you could check first if your object is already in the list:
if object1 not in my_list:
my_list.append(object1)
Upvotes: 0
Reputation: 33
The computer does only what you tell it to do. So if you append something twice, it will listen. If you want it to do it under a condition, you need to use an if statement and compare the values within the list to the value you are trying to add. To make this easier, I would put this in a function so you can call this logic easily
In your case, I'm assuming you only want to add the object if it doesn't exist:
list = []
def addToList(elem):
global list # allows the function to modify this variable that would be normally out of scope
if elem not in list:
list.append(elem)
object1 = [1,2,3]
addToList(object1)
addToList(object1)
print(list)
Upvotes: 1