Finding the index of an item in a list

后端 未结 30 3338
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  失恋的感觉
    2020-11-21 06:03

    There is a chance that that value may not be present so to avoid this ValueError, we can check if that actually exists in the list .

    list =  ["foo", "bar", "baz"]
    
    item_to_find = "foo"
    
    if item_to_find in list:
          index = list.index(item_to_find)
          print("Index of the item is " + str(index))
    else:
        print("That word does not exist") 
    

提交回复
热议问题