naughty_waves
naughty_waves

Reputation: 275

Is it possible to limit the number of iterations and also store the iterator items in a list using itertools?

I have a bunch of lines (over 50 in total) that are to appear in several plots, and I would like to store them using numerous markers. Alas, the number of markers in matplotlib is limited to the extent that the number is eclipsed by the number of lines. After spending an hour looking for an answer here, I identified itertools.cycle as a potential solution since it allows me to cycle through a series. Say, for example, I want to cycle through five markers:

import itertools    
markers = itertools.cycle(('o', 'D', '*', 'X', '+'))

However, I soon realized the necessity of limiting the cycle to a certain number (i.e. the number of lines) and storing them in a list because the lines will appear in several plots and I would like for the markers to be consistent. I came across another question (Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?) that appears to solve the limited part of my problem by:

import itertools
n = 50 # number of lines
itertools.chain.from_iterable(itertools.repeat(['o', 'D', '*', 'X', '+'], n))

So, now I only need to figure out the storing part of my problem.

If itertools is not the most convenient way, I would appreciate if someone could point me in a more convenient direction.

Upvotes: 1

Views: 526

Answers (1)

sturdeac
sturdeac

Reputation: 36

Since the itertools.chain is an iterable object I just ran the list function on the result of the itertools.chain.from_iterable constructor like so:

import itertools
n = 50 # number of lines
list(itertools.chain.from_iterable(itertools.repeat(['o', 'D', '*', 'X', '+'], n)))

And got the result in a list. The list ended up having length 250 because it iterated through the entire series 50 times.

I hope this helps.

Edit:

Of course, if you want to use the list just set a variable to the result like so:

var_name = list(itertools.chain.from_iterable(itertools.repeat(['o', 'D', '*', 'X', '+'], n)))

Upvotes: 1

Related Questions