PiccolMan
PiccolMan

Reputation: 5366

How to check if a list has a certain element in it

my_list = ["hi", "bye", "hi"]

Say I don't know what is in my_list, how can I check if "bye" is an element in my list. And if "bye" is an element in my_list, then how can I know which index it has (for this case "bye" is in my_list[1])?

Upvotes: 0

Views: 258

Answers (4)

m0bi5
m0bi5

Reputation: 9462

You can use the in operator to check if a specific item exists in a list. To find the index of any item in a list just use the .index() function. If you are a beginner in Python you can use the below method else you can check out exception handling.

my_list = ["hi", "bye", "hi"]
if 'bye' in my_list:
   print "Word found at index %i",my_list.index('bye')
else
   print 'Word not Found !'

Upvotes: 0

Loocid
Loocid

Reputation: 6441

how can I check if "bye" is an element in my list.

"bye" in my_list

then how can I know which index it is

my_list.index("bye")

You can skip the first step because if you try to find the index of a value that isn't in the list, you will get a value error which you can handle like this:

try:
    my_list.index("not here")
except ValueError:
    print("'not here' isn't in the list!!")

Upvotes: 6

Haleemur Ali
Haleemur Ali

Reputation: 28253

you can try list.index.

try:
    i = my_list.index('hi')
except ValueError:
    i = False

i will hold the index if hi is in the list, otherwise it will be False, because list.index raises ValueErrror if it can't return the index.

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

try:
    idx = ['hi', 'bye', 'hi'].index('bye')
except ValueError:
    print('Not in list.')
else:
    print('In list at index', idx)

Upvotes: 2

Related Questions