English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode index() recherche un élément dans la tuple et retourne son index.
En un mot, la méthode index() recherche l'élément donné dans la tuple et retourne sa position.
Cependant, si l'élément apparaît plusieurs fois, la méthode retourne la position de la première apparition.
Remarque : Rappelez-vous que les indices en Python commencent à 0, pas à1。
tupleLa syntaxe de la méthode index() est :
tuple.index(element)
The index() method takes one parameter:
element-The element to be searched
The index method returns the position of the given element in the tuple/Index.
If no element is found, a ValueError exception will be raised indicating that the element is not found.
# Vowel tuple vowels = ('a', 'e', 'i', 'o', 'i', 'u') # Element 'e' is searched index = vowels.index('e') # Print index print('e index:', index) # Element 'i' is searched index = vowels.index('i') # Only print the first index of the element print('i index:', index)
When running this program, the output is:
e index: 1 i index: 2
# Vowel tuple vowels = ('a', 'e', 'i', 'o', 'u') # Element 'p' is searched index = vowels.index('p') # index is printed print('p index value:', index)
When running this program, the output is:
ValueError: tuple.index(x): x not in tuple
# Random tuple random = ('a', ('a', 'b'), [3, 4]") # Element ('a', 'b') is searched index = random.index(('a', 'b')) # index is printed print("('a', 'b') index:", index) # Element [3, 4] is searched index = random.index([3, 4]") # index is printed print("[3, 4] Index:
When running this program, the output is:
('a', 'b') index: 1 [3, 4] Index: 2