How can we access the index in ‘for’ loops ?

How can we access the index in ‘for’ loops ?

Asked on December 20, 2018 in Python.
Add Comment


  • 3 Answer(s)

    The solution for the question is,

        We can use the built-in function enumerate(), available in both Python 2 & 3

    for idx, val in enumerate(ints):
      print(idx, val)
    
    Answered on December 20, 2018.
    Add Comment

    Let us discuss the solution,

        The simplest way is to start it from other than 0

    for index, item in enumerate(iterable, start=1):
    print index, item
    

    Note:

    Though a little misleading since index will be a tuple (idx, item) here

    Answered on December 20, 2018.
    Add Comment

    Here is the solution,

        We can access by using the code below

    for i in range(len(ints)):
      print i, ints[i]
    
    Answered on December 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.