user26334
user26334

Reputation: 11

Alternative to next(next(...)) to access n-th elemnt of iterator

I have a list iterator children equivalent to <list_iterator object at 0x050BAAF0> (VS-Code debugger), and need to access the 4th element of that iterator, which I know for sure exists.

Is there a quick way, instead of calling 4 times next(children) to access an element at the n-th position in a list iterator, without having the list itself.

Thanks!

EDIT: here is some code: the iterator is actually the children of a BeautifulSoup node of a div

virgin_url = "https://www.clicpublic.be/product/_"
product_soup = get_soup(virgin_url + single_id + ".html") 
#get_soup returns the BeatutifulSoup([HTML of page])
bs_info_list = product_soup.findAll("div", {'class': "txtProductInformation"}
children = bs_info_list[0].children

Upvotes: 1

Views: 127

Answers (1)

kederrac
kederrac

Reputation: 17322

you can use itertool.islice:

from itertools import islice

next(islice(children, 3, None))

The 4th element has index 3

ex:

from itertools import islice

children = (e for e in range(100))
next(islice(children, 3, None))

output:

3

Upvotes: 1

Related Questions