0

I have the following tuple :

mytuple = (("azerty", "1"), ("qwerty", "2"))

I am trying to check if a variable is not in it:

n = 'azerty'

if n not in mytuple:
    print('not in the list')

> not in the list

I am trying to match the string "azerty" to each tuple in the tuple, So I tried to go 1 more layer into the tuple:

for mylist in mytuple:
    if n not in mylist:
        print('not in the list')

> not in the list

Now the problem here is mytuple[1] is matching my if, making me print.

Do you know how can I check if my variable is not in a tuple?

EDIT: This question was marked as duplicate. However, the answered post refers to a slightly different problem. The original post checks existence by index and this problem wants to check existence for any element in the tuple.

Arturo Sbr
  • 5,567
  • 4
  • 38
  • 76
molik
  • 51
  • 5
  • 2
    You may find the builtin [`any`](https://docs.python.org/3/library/functions.html#any) helpful here – Brian61354270 Mar 16 '21 at 14:24
  • 3
    `if not any(i[0] == n for i in mytuple)`, `if n not in map(itemgetter(0), mytuple)` – deceze Mar 16 '21 at 14:25
  • 2
    `any("azerty" == a for a, b in mytuple)`. Note that `mytuple` is not a tuple, it is a list... – Samwise Mar 16 '21 at 14:25
  • As a quick comment, you actually are not working with tuples in this problem. You declared a list. Tuples are enclosed in parenthesis `()`, and lists are enclosed in brackets `[]`. – Arturo Sbr Mar 16 '21 at 14:26
  • @Arturo oops i made a mistake while typing. It is a tuple, i will edit – molik Mar 16 '21 at 14:29

1 Answers1

1

Or you can do:

general_list = [("azerty", "1"), ("qwerty","2")]
n = "azerty"
in_tuple = False
for single_tuple in general_list:
    if n in single_tuple:
        in_tuple = True
if not in_tuple:
    print("not in the list")
David Meu
  • 1,527
  • 9
  • 14