Reputation: 49
Python enumeration function enumerate takes one argument start. What is the use of this argument ? If i write some code using this argument it shifts only index e.g.
>>a=[2,3,4,5,6,7]
>>for index,value in enumerate(a,start=2):
... print index,value
...
**2 2**
3 3
4 4
5 5
6 6
7 7
8 8
So index is changed to 2 ,Not Value.Value is still started from first element. Why this is so ? In place of this functionality ,It could be better if value is started from that index rather than starting element. What was the thinking behind the implementation of this ?
Upvotes: 0
Views: 862
Reputation: 87124
enumerate()
associates a sequence of integers with an iterable, i.e. it enumerates the items of the sequence. Its argument start
is not meant to affect the starting position within the iterable, just the initial value from which to start counting.
One use is to start the enumeration from 1 instead of 0, e.g. if you wanted to number the lines in a file:
with open('file.txt') as f:
for line_number, line in enumerate(f, 1):
print(line_number, line)
This outputs the line numbers starting from 1, which is where most users would expect line numbering to begin.
If you want to skip the first n items in a sequence you can just slice it:
a = [2,3,4,5,6,7]
n = 2
for index, value in enumerate(a[n:]):
print index, value
outputs
0 4 1 5 2 6 3 7
but you might like to start the enumeration from 3 as well:
a = [2,3,4,5,6,7]
n = 2
for index, value in enumerate(a[n:], n+1):
print index, value
which would output
3 4 4 5 5 6 6 7
Upvotes: 2
Reputation: 3785
Some people - most I suppose - aren't used to an enumerated list starting at zero. At the very least, this makes it easy to format the output so the enumeration starts at one, e.g.
a = ['Fred', 'Ted', 'Bob', 'Alice']
for index, value in enumerate(a, start=1):
print index, value
will print out:
1 Fred
2 Ted
3 Bob
4 Alice
Without the start=1
parameter, enumerate(a)
would print
0 Fred
1 Ted
2 Bob
3 Alice
https://docs.python.org/2/library/functions.html#enumerate
Upvotes: 0