+ Reply to Thread
Results 1 to 3 of 3

Thread: finding and printing index in a loop

  1. #1

    finding and printing index in a loop

    hi again,

    can't seem to figure out a way to print a nested lists index while iterating through it.

    for example lets say i have a list group that has nested lists of points

    Python Code:
      for i in group:
          for j in i:
              print "index no." + str(i) + str(j)

    the str(i) will give me the complete items inside the nested list 'i', but not the index number, meaning whether 'j' is in 'i' position of 0, 1, 2 or even the 'j' position inside 'i' etc. If i want to check the script usually i use print commands in order to understand where the mistake is or where the script crashes.

    I've tried many ways, but I don't know how to print the index no. and for sure a counter is not a sophisticated way !

    any help appreciated.

    Pav

  2. #2
    Super Moderator Mitch's Avatar
    Join Date
    May 2010
    Location
    Switzerland
    Posts
    285
    Hi,

    You could use the Python built-in function 'Enumerate'. Enumerate will iterate over a sequence and return each element and its index.
    Python Code:
      #create list (just a simple example)
      group=[]
      for i in range (5):
          group.append([i,i,i])
       
      #now enumerate the list
      for (n,element) in enumerate(group):
          print "Element index "+str(n)+" is: ",element
    For each index in the list, you get a tuple composed of (index, element)
    HTH, --Mitch

  3. #3
    thanks Mitch,


    that's all i need

    Pav

+ Reply to Thread

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts