Reputation: 335
I am fairly new to python and therefore, although I have been trying to find a solution to this problem since hours, I cant! I have a list of tuples called list_of_tuples and then another list of tuples which is called finalTuple and to which I have appended two tuples. What I wanna do is read all of the tuples from the list_of_tuples and figure out if there is already an identical tuple in the list. If there is one I wanna print a message in the console which indicates that otherwise just append the tuple in the finalTuple. Could someone help me with that? I have tried the following code but it doesnt work:
list_of_tuples = [ ("a","b","c"),
("a","b","c"),
("a","b","d"),
("a","b","d"),
("i","k","l")
]
first_tuple = ("a","b","c")
second_tuple= ("a","b","d")
finalTuple = []
finalTuple.append(first_tuple)
finalTuple.append(second_tuple)
for i in range(len(list_of_tuples)):
# print(listtt[i])
if not(any((list_of_tuples[i]) in j for j in finalTuple)) :
key_value = []
key_value.append(list_of_tuples[i])
finalTuple.append(tuple(key_value))
print("The tuple is appended to the list")
if (any((list_of_tuples[i]) in j for j in finalTuple)) :
print("The value already exists")
The output I am getting on the console is:
PS C:\Users\andri\PythonProjects\mypyth> py test.py
The tuple is appended to the list
The value already exists
The value already exists
The tuple is appended to the list
The value already exists
The value already exists
The tuple is appended to the list
The value already exists
Upvotes: 1
Views: 4545
Reputation: 23753
lot = [("a","b","c"),
("a","b","c"),
("a","b","d"),
("a","b","d"),
("i","k","l")]
ft = [("a","b","c"),("a","b","d")]
Use in
or not in
for membership testing .
>>> for thing in lot:
... if thing in ft:
... print(f'{thing} in ft')
... else:
... ft.append(thing)
('a', 'b', 'c') in ft
('a', 'b', 'c') in ft
('a', 'b', 'd') in ft
('a', 'b', 'd') in ft
>>> ft
[('a', 'b', 'c'), ('a', 'b', 'd'), ('i', 'k', 'l')]
>>>
Or use sets for membership testing.
>>> set(lot).difference(ft)
{('i', 'k', 'l')}
>>> ft.extend(set(lot).difference(ft))
>>> ft
[('a', 'b', 'c'), ('a', 'b', 'd'), ('i', 'k', 'l')]
>>>
Upvotes: 1
Reputation: 106553
Your if
block that checks if the value already exists takes place after the if
block that checks if it doesn't, append the value to the list, so the former is always True
since the value would be appended to the list even if it did not. You should use an else
block for the opposite condition instead. Moreover, to check if a tuple already exists in a list of tuples, you can simply use the in
operator instead:
for i in range(len(list_of_tuples)):
if list_of_tuples[i] in finalTuple:
print("The value already exists")
else:
finalTuple.append(list_of_tuples[i])
print("The tuple is appended to the list")
Upvotes: 2