How can I check if a tuple exists in a Python list?
I am new to Python and I am trying to check if a pair exists [a,b]
in the list l=[[a,b],[c,d],[d,e]]
. I searched a lot of questions but couldn't find the exact solution. Please can someone tell me the correct and shortest way to do this?
when i run:
a=[['1','2'],['1','3']]
for i in range(3):
for j in range(3):
if [i,j] in a:
print a
OUTPUT BLOCKED.
how to do it?
The code doesn't work because, '1' != 1
and therefore, ['1','2'] != [1,2]
If you want it to work, try:
a=[['1','2'],['1','3']]
for i in range(3):
for j in range(3):
if [str(i), str(j)] in a: # Note str
print a
(But using in
or sets, as mentioned, is better)
Here's an example:
>>> [3, 4] in [[2, 1], [3, 4]]
True
If you need to do this many times, consider using it because it has a much faster containment check. set
In my interpreter (IPython 0.10, Python 2.7.2+), your code gives the correct output:
In [4]: a=[[1,2],[1,3]]
In [5]: for i in range(3):
...: for j in range(3):
...: if [i,j] in a:
...: print a
...:
[[1, 2], [1, 3]]
(This should be a comment, but I cannot leave them.)
EDIT:
It turns out you had strings in the list a
. Then you need to convert yours int
to str
:
a=[['1','2'],['1','3']]
for i in range(3):
for j in range(3):
if [str(i), str(j)] in a:
print a
This code works great for me:
>>> a = [[1, 2], [3, 4], [13, 11]]
>>>
>>> for i in range(10):
... for j in range(10):
... if [i, j] in a:
... print [i, j]
...
[1, 2]
[3, 4]
>>>
I'm not sure what is wrong with your code. You probably don't have "]" in the first line.
Don't forget that [a, b] is not [b, a] in python, so you can order 2 values ββin your tuples if you want to consider [A, B] and [B, A] the same thing:
You can also use set (your_list) if your list is large and redundant.
In the example code, you are compiling integers and strings:
['1', '2'] # this is a 2-list of strings '1' and '2'
[1, 2] # this is a 2-list of integers 1 and 2