By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead but how can we enumerate from a particular value of count and elem. for example, we want to pass count as '2' and elem as 'bar'. both values have to pass to enumerate function.
elements = ('foo', 'bar', 'baz')
for count, elem in enumerate(elements):
print (count, elem)
You can iterate a slice of your data and start the enumeration at a specific integer:
start_at = 1
elements = ('foo', 'bar', 'baz')
for count, elem in enumerate(elements[start_at:], start_at):
print (count, elem)
Output:
1 bar
2 baz
Documentation:
start
to start numbering the 0th element of iterable
with that number onwards)Edit:
If you are working with non-sliceable iterators you have to work around it:
start_at = 3 # first one included (0 based)
stop_at = 5 # last one (not included)
elements = ('foo', 'bar', 'baz', 'wuzz', 'fizz', 'fizzbuzz', 'wuzzfizzbuzz', 'foobarfuzzbizzwuzz')
# skip first few
it = iter(elements)
for _ in range(start_at):
print("skipping: ", next(it)) # dont print, simply: next(it)
# enumerate the ones you want
i = start_at
for _ in range(stop_at-start_at):
print(i,next(it)) # you might need a try: except StopIteration:
i+=1
to get:
skipping: foo
skipping: bar
skipping: baz
3 wuzz
4 fizz
5 fizzbuzz
the itertools module is where you should look when you want to iterate in a non standard way
in this case use islice
to get the start index, use the .index
function of the container(or hardcode it to 1 if you want to iterate from the second position regardless of the contents), the end index is the len
of the container
for count, elem in enumerate(itertools.islice(elements, elements.index('bar'), len(elements))
print(count, elem)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With