In Python, you can get the element and index [count] from iterable objects such as list
and tuple
in for
loop with the built-in function enumerate[]
.
- Built-in Functions - enumerate[] — Python 3.8.5 documentation
This article describes the following contents.
- How to use
enumerate[]
- Normal
for
loop for
loop withenumerate[]
- Normal
- Start index at 1 with
enumerate[]
- Set step with
enumerate[]
See the following articles for more information about for
loop and how to use enumerate[]
and zip[]
together.
- for loop in Python [with range, enumerate, zip, etc.]
- Use enumerate[] and zip[] together in Python
How to use enumerate[]
Normal for
loop
l = ['Alice', 'Bob', 'Charlie']
for name in l:
print[name]
# Alice
# Bob
# Charlie
for
loop with enumerate[]
By passing an iterable object to enumerate[]
, you can get index, element
.
for i, name in enumerate[l]:
print[i, name]
# 0 Alice
# 1 Bob
# 2 Charlie
Start index at 1 with enumerate[]
As in the example above, by default, the index of enumerate[]
starts at 0.
If you want to start from another number, pass the number to the second
argument of enumerate[]
.
Start at 1:
for i, name in enumerate[l, 1]:
print[i, name]
# 1 Alice
# 2 Bob
# 3 Charlie
Start at the other number:
for i, name in enumerate[l, 42]:
print[i, name]
# 42 Alice
# 43 Bob
# 44 Charlie
For example, this is useful when generating sequential number strings starting from 1. It is smarter to pass the starting number to the second argument of enumerate[]
than to calculate i + 1
.
for i, name in enumerate[l, 1]:
print['{:03}_{}'.format[i, name]]
# 001_Alice
# 002_Bob
# 003_Charlie
Set step with enumerate[]
There is no argument like step
to specify increment to enumerate[]
, but it can be done as follows.
step = 3
for i, name in enumerate[l]:
print[i * step, name]
# 0 Alice
# 3 Bob
# 6 Charlie
I am using Python 2.5, I want an enumeration like so [starting at 1 instead of 0]:
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
I know in Python 2.6 you can do: h = enumerate[range[2000, 2005], 1] to give the above result but in python2.5 you cannot...
Using Python 2.5:
>>> h = enumerate[range[2000, 2005]]
>>> [x for x in h]
[[0, 2000], [1, 2001], [2, 2002], [3, 2003], [4, 2004]]
Does anyone know a way to get that desired result in Python 2.5?
Seanny123
7,99312 gold badges65 silver badges117 bronze badges
asked Jul 21, 2010 at 20:37
3
As you already mentioned, this is straightforward to do in Python 2.6 or newer:
enumerate[range[2000, 2005], 1]
Python 2.5 and older do not support the start
parameter so instead you could create two range objects and zip them:
r = xrange[2000, 2005]
r2 = xrange[1, len[r] + 1]
h = zip[r2, r]
print h
Result:
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
If you want to create a generator instead of a list then you can use izip instead.
answered Jul 21, 2010 at 20:41
Mark ByersMark Byers
780k183 gold badges1551 silver badges1440 bronze badges
5
Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so:
enumerate[sequence, start=1]
answered Feb 6, 2013 at 18:28
dhacknerdhackner
2,8222 gold badges19 silver badges23 bronze badges
1
Python 3
Official Python documentation: enumerate[iterable, start=0]
You don't need to write your own generator as other answers here suggest. The built-in Python standard library already contains a function that does exactly what you want:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list[enumerate[seasons]]
[[0, 'Spring'], [1, 'Summer'], [2, 'Fall'], [3, 'Winter']]
>>> list[enumerate[seasons, start=1]]
[[1, 'Spring'], [2, 'Summer'], [3, 'Fall'], [4, 'Winter']]
The built-in function is equivalent to this:
def enumerate[sequence, start=0]:
n = start
for elem in sequence:
yield n, elem
n += 1
answered Jun 23, 2019 at 11:52
winklerrrwinklerrr
10.5k5 gold badges65 silver badges80 bronze badges
Easy, just define your own function that does what you want:
def enum[seq, start=0]:
for i, x in enumerate[seq]:
yield i+start, x
answered Jul 21, 2010 at 20:44
DuncanDuncan
88k10 gold badges116 silver badges155 bronze badges
Simplest way to do in Python 2.5 exactly what you ask about:
import itertools as it
... it.izip[it.count[1], xrange[2000, 2005]] ...
If you want a list, as you appear to, use zip
in lieu of it.izip
.
[BTW, as a general rule, the best way to
make a list out of a generator or any other iterable X is not [x for x in X]
, but rather list[X]
].
answered Jul 21, 2010 at 21:48
Alex MartelliAlex Martelli
823k163 gold badges1202 silver badges1379 bronze badges
from itertools import count, izip
def enumerate[L, n=0]:
return izip[ count[n], L]
# if 2.5 has no count
def count[n=0]:
while True:
yield n
n+=1
Now h = list[enumerate[xrange[2000, 2005], 1]]
works.
answered Jul 21, 2010 at 20:43
Jochen RitzelJochen Ritzel
102k29 gold badges195 silver badges190 bronze badges
0
enumerate is trivial, and so is re-implementing it to accept a start:
def enumerate[iterable, start = 0]:
n = start
for i in iterable:
yield n, i
n += 1
Note that this doesn't break code using enumerate without start argument. Alternatively, this oneliner may be more elegant and possibly faster, but breaks other uses of enumerate:
enumerate = [[index+1, item] for index, item]
The latter was pure nonsense. @Duncan got the wrapper right.
answered Jul 21, 2010 at 20:49
1
>>> list[enumerate[range[1999, 2005]]][1:]
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
answered Jul 21, 2010 at 21:06
JABJAB
20.2k6 gold badges68 silver badges79 bronze badges
3
h = [[i + 1, x] for i, x in enumerate[xrange[2000, 2005]]]
answered Jul 21, 2010 at 20:39
Chris B.Chris B.
80.8k25 gold badges95 silver badges136 bronze badges
3
Ok, I
feel a bit stupid here... what's the reason not to just do it with something like
[[a+1,b] for [a,b] in enumerate[r]]
? If you won't function, no problem either:
>>> r = range[2000, 2005]
>>> [[a+1,b] for [a,b] in enumerate[r]]
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
>>> enumerate1 = lambda r:[[a+1,b] for [a,b] in enumerate[r]]
>>> list[enumerate1[range[2000,2005]]] # note - generator just like original enumerate[]
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
answered Jul 22, 2010 at 3:55
Nas BanovNas Banov
27.8k6 gold badges46 silver badges67 bronze badges
>>> h = enumerate[range[2000, 2005]]
>>> [[tup[0]+1, tup[1]] for tup in h]
[[1, 2000], [2, 2001], [3, 2002], [4, 2003], [5, 2004]]
Since this is somewhat verbose, I'd recommend writing your own function to generalize it:
def enumerate_at[xs, start]:
return [[tup[0]+start, tup[1]] for tup in enumerate[xs]]
answered Jul 21, 2010 at 20:41
Eli CourtwrightEli Courtwright
179k65 gold badges208 silver badges256 bronze badges
1
I don't know how these posts could possibly be made more complicated then the following:
# Just pass the start argument to enumerate ...
for i,word in enumerate[allWords, 1]:
word2idx[word]=i
idx2word[i]=word
answered May 27, 2019 at 17:00
bmcbmc
8071 gold badge12 silver badges18 bronze badges