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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemple de index() en liste Python

Python list methods

La méthode index() recherche l'élément dans la liste et renvoie sa valeur d'index.

En résumé, la méthode index() dansList inFind the given element and return its position.

If the same element appears multiple times, this method returns the index of the first occurrence of the element.

Note: Note: In Python, indexing starts from 0, not1.

The syntax of the index() method is:

list.index(element)

index() parameter

The method has one parameter:

  • element -The element to be searched for.

index() return value

The method returns the index of the element in the list.

If the element is not found, it will raise a ValueError exception indicating that the element is not in the list.

Example1: Find the position of the element in the list

# Vowel list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# Index of 'e'
index = vowels.index('e')
print('Index value of e:', index)
# Index of the first 'i'
index = vowels.index('i')
print('Index value of i:', index)

Output result

Index value of e: 1
Index value of i: 2

Example2: Index of an element not in the list

# Vowel list
vowels = ['a', 'e', 'i', 'o', 'u']
# 'p' does not exist in the list
index = vowels.index('p')
print('Index value of p:', index)

Output result

ValueError: 'p' is not in list

Example3: Find the index of the tuple and list it in the list

# Random list
random = ['a', ('a', 'b'), [3, 4]
# Index of ('a', 'b')
index = random.index(('a', 'b'))
print("Index of ('a', 'b'):", index)
# [3, 4] index
index = random.index([3, 4]
print("[3, 4] Index:

Output result

Index of ('a', 'b'): 1
[3, 4] Index: 2

Python list methods