Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate from the middle of tuple [duplicate]

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)
like image 359
aryan Avatar asked Dec 23 '22 01:12

aryan


2 Answers

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:

  • enumerate(iterable, start=0) (specify whatever for 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
like image 94
Patrick Artner Avatar answered Dec 25 '22 15:12

Patrick Artner


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)
like image 43
Derte Trdelnik Avatar answered Dec 25 '22 14:12

Derte Trdelnik