Techie5879
Techie5879

Reputation: 595

How to check if all elements of a tuple are elements of other tuple in python?

So I have two tuples, lets say seq_a and seq_b. I want to print "True" if every element of seq_a is also an element of seq_b.

Please don't suggest a function, I want it done using loops, or if-else etc

I tried using the for loop but can't quite figure out the syntax.

seq_a = eval(input("Enter a tuple: "))
seq_b = eval(input("Enter a tuple: "))


for i in seq_a:
    if i in seq_b:
        print("True")
    break
else:
    print("False")

Upvotes: 0

Views: 1925

Answers (4)

Mad Wombat
Mad Wombat

Reputation: 15105

There are a few ways. The "in your face" way is to use a loop

result = True
for i in seq_a:
    if i not in seq_b:
        result = False
        break
print(str(result))

you could do the same thing using list comprehensions

result = all(i in seq_b for i in seq_a)
print(str(result))

or as suggested by one of the other answers, you could use set operations

result = set(seq_a).issubset(set(seq_b))
print(str(result))

Upvotes: 1

person
person

Reputation: 458

Why don't you just tweak your code so it remembers if something isn't in the other tuple?

all_the_same = true
for i in seq_a:
    if i not in seq_b:
        all_the_same = False
        break

print(all_the_same)

Alternatively, write a function to just return whether or not they're the same:

function test_tuples(seq_a,seq_b):
  for i in seq_a:
    if i not in seq_b:
        return False
  return True

print(test_tuples(seq_a,seq_b))

Upvotes: 0

Charlie Martin
Charlie Martin

Reputation: 112366

Convert the tuples to Sets and use set difference.

 Set(tuple1)-Set(tuple2) 

Upvotes: -1

Djaouad
Djaouad

Reputation: 22776

You can print "False" and break when i is not in seq_b, and if all are (the else clause), print "True":

for i in seq_a:
    if i not in seq_b:
        print("False")
        break
else:
    print("True")

Upvotes: 2

Related Questions