0

how do i find a certain element in a tuple and print out the index of the element.


a = (1,2,3,4)
b = int(input('enter the element you want to find'))
if b in a :
    print('found')

here is the simple program. now how do print the index of the element whic needs to be searched

  • Does this answer your question? [Finding the index of an item in a list](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – Mast Feb 01 '23 at 20:25

3 Answers3

2

Use .index:

if b in a:
    print(a.index(b))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use enumerate as well:

enumerate

a = (1,2,3,4)
b = int(input('enter the element you want to find'))
for x,y in enumerate(a):
    if b == y:
        print(x)

Edit:

to find the multiple indices of an element:

Suppose we have b at 3 positions, now if you want to find all the three indices then:

a = (1,2,3,4,5,6,2,8,2)
b = 2

for i, x in enumerate(a):
    if x == b:
        print(i)
1
6
8

with list comprehension :

[i for i, x in enumerate(a) if x == b]
#[1, 6, 8]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0

Use:

print(a.index(b))

Use this link for working with tuples