In this post, we are going to learn 4 Ways to find index value of all list items in Python. We will learn this with the help of examples.
1.Simple Method using loop
The simple method to Find index-value of all list items is for loop.We are iterating over the list items and printing value and index.
LangList = ['C#', 'python', 'C', 'Java', 'Go']
# simple method to get the index of an item
print ("LangList index-value are : ")
for j in range(len(LangList)):
print (j , end = " ")
print (LangList[j])
Output
LangList index-value are :
0 C#
1 python
2 C
3 Java
4 Go
2. Using list comprehension
In this code example, we are using the list comprehension to find the index and value of all items of python list.
LangList = ['C#', 'python', 'C', 'Java', 'Go']
# get index and value by list comprehension
print ("LangList index-value are : \n")
print ([list((j, LangList[j])) for j in range(len(LangList))])
Output
LangList index-value are :
[[0, 'C#'], [1, 'python'], [2, 'C'], [3, 'Java'], [4, 'Go']]
3. Using enumerate()
In this code example we are using the enumerate() method to get the index and value of an item in python list.
LangList = ['C#', 'python', 'C', 'Java', 'Go']
# get index and value by using enumerate
print ("LangList index-value are : \n")
for index, value in enumerate(LangList):
print(index, value)
Output
LangList index-value are :
0 C#
1 python
2 C
3 Java
4 Go
4. Using Zip() method
In this code example we are using the zip() method to get the index and value of an item in python list.
LangList = ['C#', 'python', 'C', 'Java', 'Go']
# get index and value by using zip
print ("LangList index-value are : \n")
for index, value in zip(range(len(LangList)), LangList):
print(index, value)
Output
LangList index-value are :
0 C#
1 python
2 C
3 Java
4 Go
5.Using list.index() Method
In this code example, we are using the list built in method index() to get the index of an item.
LangList = ['C#', 'python', 'C', 'Java', 'Go']
item_to_find = 'C#'
# get index and value by using zip
print("Index of item c# :",LangList.index(item_to_find))
Output
Index of item c# : 0