0

I want to find if the first element or the second element matches 3, if so I want to append the tuple to mytuple_with_3.

mytuple=[(1,3),(4,9),(3,8)]
mytuple_with_3 = []

c = 0
for x in mytuple:
    if x[0][c] == 3 or x[c][1] == 3:
        mytuple_with_3.append(x)
    c += 1

result show show (1,3) and (3,8)

Xi N
  • 45
  • 1
  • 9
  • Some basic level of googling "list comprehension to filter tuple" should have found you a solution. – cs95 Oct 09 '18 at 21:49

1 Answers1

1

Use this list comprehension:

mytuple_with_3 = [i for i in mytuple if 3 in i]

>>> mytuple_with_3
[(1, 3), (3, 8)]

To limit it to only the first 2 elements, use:

mytuple_with_3 = [i for i in mytuple if 3 in i[:2]]
sacuL
  • 49,704
  • 8
  • 81
  • 106