By Joan Venge


2009-02-06 22:47:54 8 Comments

How do I access the index itself for a list like the following?

ints = [8, 23, 45, 12, 78]

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

22 comments

@RIshu 2018-06-10 03:59:43

If there is no duplicate value in the list:

for i in ints:
    indx = ints.index(i)
    print(i,indx)

Otherwise use enumerate.

for counter, value in enumerate(ints):
    print(counter, value)

OR use below:

for counter in range(len(ints)):
    print(counter, ints[counter])

@Saheli Mukherjee 2018-11-30 09:25:05

It can also be done by using the index() method

for i in ints:
   print(ints.index(i), i) 

Here the indexing starts from 0. But in case you need to start it from 1 just add 1 to the index() method as follows

for i in int:
   print(int.index(i) + 1, i)    

@pushkin 2018-11-30 18:14:33

This is a duplicate of the answer by Sumit Kumar. Also, as stated there in a comment, this won't work if the list has duplicate elements

@DrM 2018-08-15 17:52:50

In you question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list, runs from zero. So, then we need to known if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in python it is easy to do either or both.

First, to clarify, the enumerate function, iteratively returns the index and corresponding item for each item in a list.

alist = [ 1, 2, 3, 4, 5 ]

for n,a in enumerate(alist):
    print( "%d %d"%(n,a) )

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including python and c.

If you want your loop to span a part of the list, you can use the standard python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n,a in enumerate(alist[1:-1]):
    print( "%d %d"%(n,a) )

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n,a in enumerate(alist,start=1):
    print( "%d %d"%(n,a) )

for which the output is

1 1
2 2
3 3
4 4
5 5

@Clayton 2014-05-27 10:04:52

It's pretty simple to start it from 1 other than 0:

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

Note

Important hint, though a little misleading since index will be a tuple (idx, item) here. Good to go.

@Antti Haapala 2016-03-18 09:18:40

The question was about list indexes; since they start from 0 there is little point in starting from other number since the indexes would be wrong (yes, the OP said it wrong in the question as well). Otherwise, calling the variable that is tuple of index, item just index is very misleading, as you noted. Just use for index, item in enumerate(ints).

@hygull 2018-01-02 11:31:38

Better is to enclose index inside parenthesis pairs as (index), it will work on both the Python versions 2 and 3.

@pushkin 2018-11-30 18:24:48

@AnttiHaapala The reason, I presume, is that the question's expected output starts at index 1 instead 0

@Ankur Kothari 2018-06-04 02:10:17

If I were to iterate nums = [1,2,3,4,5] I would do

for i, num in enumerate(nums, start = 1):
    print(i, num)

Or get the length as l = len(nums)

for i, num in range(1, l + 1):
    print(i, nums[i])

@skelliam 2018-10-28 14:33:40

Second example is incorrect. range() in this context returns a single int, so the for i, num part will fail. Secondly, you cannot access nums[i] if your range is from 1 to len+1. the second line would fail anyway because i would be out of range. The correct use of range in this case would be for i in range(len(nums)): print(nums[i])

@killerT2333 2018-05-30 21:34:22

You can use the index method

ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]

EDIT Highlighted in the comment that this method doesn’t work if there are duplicates in ints, the method below should work for any values in ints:

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]

Or alternatively

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]

if you want to get both the index and the value in ints as a list of tuples.

It uses the method of enumerate in the selected answer to this question, but with list comprehension, making it faster with less code.

@eyllanesc 2018-05-30 22:07:34

your solution works with: ints = [8, 8, 8, 8, 8] ?

@Sumit Kumar 2018-04-24 10:45:29

This serves the purpose well enough:

list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)

@Peter Szoldan 2018-05-15 17:17:59

This will break down if there are repeated elements in the list as index() will search for the first occurrence of x, not mentioning the O( n^2 ) time required to look up each element.

@eyllanesc 2018-05-30 22:08:05

your solution works with: list1 = [8, 8, 8, 8, 8] ?

@Sumit Kumar 2018-06-06 10:16:34

totally agreed that it won't work for duplicate elements in the list. afterall I'm also learning python.

@lola 2018-04-24 10:53:56

To print tuple of (index, value) in list comprehension using a for loop:

ints = [8, 23, 45, 12, 78]
print [(i,ints[i]) for i in range(len(ints))]

Output:

[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

@Aaron Hall 2015-01-21 17:11:49

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:

So do this:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)

@Gary R. 2018-02-14 19:20:43

You've received a number of answers explaining enumerate, but if you only need the index for accessing matching entries in two lists, there's another way that's cleaner and simpler in Python 3: zip.

For example, if you're using the index to pull out corresponding names for the numbers in your list, you could do it like this:

ints = [8, 23, 45, 12, 78]
names = ["John", "Sue", "Johannes", "Patel", "Ian"]
for int, name = zip(ints, names):
    print("{} - {}".format(name, int)

That would produce

8 - John
23 - Sue
45 - Johannes
12 - Patel
78 - Ian

@pushkin 2018-11-30 18:21:27

You're making an assumption and thus answering a question that wasn't asked

@user2912389 2013-10-28 18:17:06

I don't know if the following is pythonic or not, but it uses the Python function enumerate and prints the index and the value.

int_list = [8, 23, 45, 12, 78]
for index, value in enumerate(int_list):
   print(index, value)

Output:

0 8
1 23
2 45
3 12
4 78

@Charitoo 2017-08-15 02:17:41

As is the norm in Python there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

1. Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

2. Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

3. Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # you will have to write extra code to get the element
    index += 1  # escape infinite recursion

4. There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using itertools.chain with for. It handles nested loops better than the other examples.

@Aristide 2017-08-25 09:56:01

In point 2, access with .index() has a linear complexity, which means that your loop's complexity is now quadratic. Moreover, it doesn't work when your list contains several equal elements, since it always returns the index of the first one.

@jamylak 2018-02-10 20:04:18

@Charitoo I'm removing point 2 because it really should never be used

@arviman 2018-05-09 13:14:42

can you have multiple enumerate at the same time? Say I want I and J to be indices such that J > I, etc.? I suppose 3 would be better for that

@Ashok Kumar Jayaraman 2018-02-07 14:04:10

You can also try this:

data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
      a = (i, str(item).split('.'))
      x.append(a)
for index, value in x:
     print(index, value)

The output is

0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']

@Anurag Misra 2017-08-24 06:15:31

Best solution for this problem is use enumerate in-build python function.
enumerate return tuple
first value is index
second value is element of array at that index

In [1]: ints = [8, 23, 45, 12, 78]

In [2]: for idx, val in enumerate(ints):
   ...:         print(idx, val)
   ...:     
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)

@Andriy Ivaneyko 2016-08-04 09:49:50

The fastest way to access indexes of list within loop in Python 2.7 is to use the range method for small lists and enumerate method for medium and huge size lists.

Please see different approaches which can be used to iterate over list and access index value and their performance metrics (which I suppose would be useful for you) in code samples below:

from timeit import timeit

# Using range
def range_loop(iterable):
    for i in range(len(iterable)):
        1 + iterable[i]

# Using xrange
def xrange_loop(iterable):
    for i in xrange(len(iterable)):
        1 + iterable[i]

# Using enumerate
def enumerate_loop(iterable):
    for i, val in enumerate(iterable):
        1 + val

# Manual indexing
def manual_indexing_loop(iterable):
    index = 0
    for item in iterable:
        1 + item
        index += 1

See performance metrics for each method below:

from timeit import timeit

def measure(l, number=10000):
print "Measure speed for list with %d items" % len(l)
print "xrange: ", timeit(lambda :xrange_loop(l), number=number)
print "range: ", timeit(lambda :range_loop(l), number=number)
print "enumerate: ", timeit(lambda :enumerate_loop(l), number=number)
print "manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number)

measure(range(1000))
# Measure speed for list with 1000 items
# xrange:  0.758321046829
# range:  0.701184988022
# enumerate:  0.724966049194
# manual_indexing:  0.894635915756

measure(range(10000))
# Measure speed for list with 100000 items
# xrange:  81.4756360054
# range:  75.0172479153
# enumerate:  74.687623024
# manual_indexing:  91.6308541298

measure(range(10000000), number=100)
# Measure speed for list with 10000000 items
# xrange:  82.267786026
# range:  84.0493988991
# enumerate:  78.0344707966
# manual_indexing:  95.0491430759

As the result, using range method is the fastest one up to list with 1000 items. For list with size > 10 000 items enumerate is the winner.

Adding some useful links below:

@Surest Texas 2017-03-04 00:08:47

"readability counts" The speed difference in the small <1000 range is insignificant. It is 3% slower on an already small time metric.

@Mike Hordecki 2009-02-06 22:52:36

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

for idx, val in enumerate(ints):
    print(idx, val)

Check out PEP 279 for more.

@clozach 2018-03-31 22:16:51

As Aaron points out below, use start=1 if you want to get 1-5 instead of 0-4.

@iamjayp 2015-02-05 17:28:25

ints = [9, 23, 45, 12, 78]
ints.extend([1,2,3,4,5,6,7,8])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can extend a list. Extend means you can add multiple values at a time.

To append this list you have to write the code given below:

ints = [9, 23, 45, 12, 78]
ints.append([1])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can add a single value at a time. If you write ints.append([1]) so this will create a sub list for this element.

@Liam 2015-05-25 15:26:58

You can do it with this code:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

@ytpillai 2015-05-25 15:08:34

First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:

for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)

To get the value of an index use

list[index]

@thinker007 2012-05-05 07:10:07

According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index

Loop counter iteration

The current idiom for looping over the indices makes use of the built-in 'range' function:

for i in range(len(sequence)):
    # work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:

for i in range(len(sequence)):
    e = sequence[i]
    # work with index i and element e

or

for i, e in zip(range(len(sequence)), sequence):
    # work with index i and element e

via http://www.python.org/dev/peps/pep-0212/

@Tadeck 2013-03-31 18:24:21

This won't work for iterating through generators. Just use enumerate().

@TankorSmash 2016-08-15 18:12:50

Nowadays, the current idiom is enumerate, not the range call.

@Charlie Martin 2009-02-06 22:52:06

Old fashioned way:

for ix in range(len(ints)):
    print ints[ix]

List comprehension:

[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
... 
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print tup
... 
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>> 

@Valor Naram 2018-07-29 20:57:41

This is not wrong and is used in C/C++ and others. It's considered as non-pythonic, but can also be used in python. Like simple solutions that break it down to the source :+

@Charlie Martin 2018-07-30 00:21:07

Where does it say it's wrong?

@Valor Naram 2018-07-30 13:51:08

Some python extremists would say, don't do this. But I said it only to indicate that there is more than one possible way

@David Hanak 2009-02-06 22:49:23

for i in range(len(ints)):
   print i, ints[i]

@Ben Blank 2009-02-06 22:52:56

That should probably be xrange for pre-3.0.

@Georg Schölly 2009-02-06 23:07:36

No, unless the speed is needed one shouldn't optimize.

@Roger Pate 2009-02-07 09:38:49

One shouldn't prematurely optimize, though I agree in this case, due to having the same code work in 2.x and 3.x.

@saulspatz 2015-08-01 21:28:53

Use enumerate instead

@januarvs 2017-03-15 06:31:21

For Python 2.3 above, use enumerate built-in function since it is more Pythonic.

@adg 2017-03-31 23:18:56

Enumerate is not always better - it depends on the requirements of the application. In my current situation the relationships between the object lengths is meaningful to my application. Although I started out using enumerate, I switched to this approach to avoid having to write logic to select which object to enumerate.

@chepner 2017-09-15 23:15:20

@adg I don't see how avoid enumerate saves any logic; you still have to select which object to index with i, no?

@Arthur Tacca 2017-11-13 17:34:35

@Roger Pate: That's what Georg said. "unless the speed is needed one shouldn't optimize" is just a long way of saying "One shouldn't prematurely optimize"

Related Questions

Sponsored Content

41 Answered Questions

[SOLVED] What does the "yield" keyword do?

29 Answered Questions

[SOLVED] For-each over an array in JavaScript?

31 Answered Questions

[SOLVED] How to break out of nested loops in Java?

  • 2009-05-20 09:07:43
  • boutta
  • 986089 View
  • 1607 Score
  • 31 Answer
  • Tags:   java loops

11 Answered Questions

[SOLVED] Iterating over dictionaries using 'for' loops

28 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 2929786 View
  • 2430 Score
  • 28 Answer
  • Tags:   python list

34 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

41 Answered Questions

[SOLVED] How do I sort a dictionary by value?

38 Answered Questions

[SOLVED] Loop through an array in JavaScript

18 Answered Questions

[SOLVED] How do I remove an element from a list by index in Python?

  • 2009-03-09 18:16:11
  • Joan Venge
  • 2001833 View
  • 1127 Score
  • 18 Answer
  • Tags:   python list

Sponsored Content