Python list | index()

Syntax :   list_name.index(element, start, end)

element - The element whose lowest index will be returned.
start (Optional) - The position from where the search begins.
end (Optional) - The position from where the search ends.

Returns : Returns lowest index where the element appears.

Error : If any element which is not present is searched, it returns a ValueError

# Python3 program for demonstration 
# of list index() method 

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] 

# Will print the index of '4' in list1 
print(list1.index(4)) 

list2 = ['cat', 'bat', 'mat', 'cat', 'pet'] 

# Will print the index of 'cat' in list2 
print(list2.index('cat')) 

Output :

3
0
# Python3 program for demonstration 
# of index() method 

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] 

# Will print index of '4' in sublist 
# having index from 4 to 8. 
print(list1.index(4, 4, 8)) 

# Will print index of '1' in sublist 
# having index from 1 to 7. 
print(list1.index(1, 1, 7)) 

list2 = ['cat', 'bat', 'mat', 'cat', 
		'get', 'cat', 'sat', 'pet'] 

# Will print index of 'cat' in sublist 
# having index from 2 to 6 
print(list2.index('cat', 2, 6 )) 

Output :

7
4
3
# Python3 program for demonstration 
# of list index() method 

# Random list having sublist and tuple also 
list1 = [1, 2, 3, [9, 8, 7], ('cat', 'bat')] 

# Will print the index of sublist [9, 8, 7] 
print(list1.index([9, 8, 7])) 

# Will print the index of tuple 
# ('cat', 'bat') inside list 
print(list1.index(('cat', 'bat'))) 

Output :

3
4
发布了128 篇原创文章 · 获赞 90 · 访问量 4861

猜你喜欢

转载自blog.csdn.net/weixin_45405128/article/details/103975906