English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de la méthode index() pour les tuples Python

Python tuple methods

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)

tuple index() parameter

The index() method takes one parameter:

  • element-The element to be searched

The value returned from tuple.index()

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.

Example1: Find the position of the element in the tuple

# 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

Example2: Index of element not existing in the tuple

# 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

Example3: Find the position of the tuple and list it in the 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

Python tuple methods