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?
source to share
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
source to share
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
source to share