Open In App

Python Program to Accessing index and value in list

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There are various methods to access the elements of a list, but sometimes we may require to access an element along with the index on which it is found. Let’s see all the different ways of accessing both index and value in a list.

Accessing index and value in list Using Naive method

This is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements. This is done using a loop. 

Python3




# Python3 code to demonstrate
# to get index and value
# using naive method
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list
print("Original list is : " + str(test_list))
  
# using naive method to
# get index and value
print("List index-value are : ")
for i in range(len(test_list)):
    print(i, end=" ")
    print(test_list[i])


Output

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
0 1
1 4
2 5
3 6
4 7

Time Complexity: O(n)
Auxiliary Space: O(1)

Accessing index and value in list Using list comprehension

This method works in similar way as the above method but uses the list comprehension technique for the same, this reduces the possible lines of code to be written and hence saves time. 

Python3




# Python3 code to demonstrate
# to get index and value
# using list comprehension
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list
print("Original list is : " + str(test_list))
  
# using list comprehension to
# get index and value
print("List index-value are : ")
print([list((i, test_list[i])) for i in range(len(test_list))])


Output

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
[[0, 1], [1, 4], [2, 5], [3, 6], [4, 7]]

Time Complexity: O(n)
Auxiliary Space: O(1)

Accessing index and value in list Using enumerate()

This is the most elegant method to perform this particular problem and is highly recommended to be used in case we require to get the index along with the value in the list. This method enumerates for index along with its value. 

Python3




# Python3 code to demonstrate
# to get index and value
# using enumerate
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list
print("Original list is : " + str(test_list))
  
# using enumerate to
# get index and value
print("List index-value are : ")
for index, value in enumerate(test_list):
    print(index, value)


Output

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
0 1
1 4
2 5
3 6
4 7

Time Complexity: O(n)
Auxiliary Space: O(1)

Accessing index and value in list Using zip()

Another method that is basically used to bind the index with the corresponding value, zip() can also be possibly used to get index along with its value. 

Python3




# Python3 code to demonstrate
# to get index and value
# using zip()
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list
print("Original list is : " + str(test_list))
  
# using zip() to
# get index and value
print("List index-value are : ")
for index, value in zip(range(len(test_list)), test_list):
    print(index, value)


Output

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
0 1
1 4
2 5
3 6
4 7

Time Complexity: O(n)
Auxiliary Space: O(1)

Accessing index and value in list Using numpy.ndenumerate()

Approach:

  1. Import the numpy module.
  2. Initialize the list.
  3. Convert the list into a numpy array.
  4. Iterate over the numpy array using the numpy.ndenumerate() function.
  5. Print the index and value of each element.

Python3




import numpy as np
  
# initializing list
test_list = [1, 4, 5, 6, 7]
   
# Printing list
print("Original list is : " + str(test_list))
  
# using numpy.ndenumerate() to get index and value
print("List index-value are : ")
for index, value in np.ndenumerate(test_list):
    print(index[0], value)


Output:

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
0 1
1 4
2 5
3 6
4 7

Time Complexity: O(n), where n is the length of the list.

Space Complexity: O(n), as we are creating a numpy array of size n.

Accessing index and value in list Using heapq

Approach:

  1. Import the heapq module.
  2. Initialize the list test_list with some values.
  3. Print out the original list test_list.
  4. Create an empty list heap to store the index and value pairs in a heap.
  5. Iterate over the list test_list using enumerate.
  6. For each index and value pair, use heapq.heappush() to add the pair to the heap list.
  7. heappush() maintains the heap property so that the smallest element in the heap is always at the root.
  8. Enter a while loop that runs until there are no more elements in the heap.
  9. Inside the loop, use heapq.heappop() to retrieve the smallest element from the heap.
  10. heappop() removes the element from the heap and returns it as a tuple containing the index and value of an element in the original list.
  11. Print out the index and value of the element.

Python3




import heapq
  
# initializing list
test_list = [1, 4, 5, 6, 7]
  
# Printing list
print("Original list is : " + str(test_list))
  
# using heapq to get index and value
print("List index-value are : ")
heap = []
for index, value in enumerate(test_list):
    heapq.heappush(heap, (index, value))
  
while heap:
    index, value = heapq.heappop(heap)
    print(index, value)
#This code is contributed by Vinay pinjala.


Output

Original list is : [1, 4, 5, 6, 7]
List index-value are : 
0 1
1 4
2 5
3 6
4 7



Previous Article
Next Article

Similar Reads

PYGLET – Accessing Index Line Property
In this article we will see how we can access index line property to the caret in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set
2 min read
Python | Accessing variable value from code scope
Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's talk about some of these functions. Method #1 : Usin
3 min read
Accessing Value Inside Python Nested Dictionaries
We are given a nested dictionary and our task is to access the value inside the nested dictionaries in Python using different approaches. In this article, we will see how we can access value inside the nested dictionaries in Python. Example: Input: market = {"fruits": {"apple": 10, "orange": 40, "strawberry": 30, "grapes": 200}, "vegetables": {"car
3 min read
PyQt5 QSpinBox - Accessing Maximum value
In this article we will see how we can get the maximum value i.e upper bound of the spin box, by default when we create a spin box it ranges from 0 to 99 i.e its maximum value is 99 although we can change this. In order to do this we will use spin_box.maximum method Syntax : spin_box.maximum() Argument : It takes no argument Return : It returns int
2 min read
PyQt5 QCalendarWidget - Accessing Base Size value
In this article we will see how we can access the base size value of the QCalendarWidget. By default base size has value zero for both width and height, base size is used to calculate a proper calendar size if the calendar defines sizeIncrement i.e its size change when window size changes. Base size is the initial size of the calendar. Base size ca
2 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python | Accessing all elements at given list of indexes
Accessing an element from its index is an easier task in Python, just using the [] operator in a Python list does the trick. But in certain situations, we are presented with tasks when we have more than one index and we need to get all the elements corresponding to those indices. Let's discuss certain ways to achieve this task. Input: list = [9, 4,
5 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Practice Tags :
three90RightbarBannerImg