Home > database >  Search For An Elemnent In A Tuple
Search For An Elemnent In A Tuple

Time:02-02

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

CodePudding user response:

Use .index:

if b in a:
    print(a.index(b))

CodePudding user response:

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]

CodePudding user response:

Use:

print(a.index(b))

Use this link for working with tuples

  • Related