Python Forum

Full Version: multiplying an iterator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if this didn't raise an exception, would you expect it to produce an iterator that multiplies this given iterator?
given = reversed('foobar')
other = 6 * given
final = ''.join(x for x in other)
print(final)
this would be expected to work if a str were assigned in line 1 (making line 3 not needed). how would you fix something like this?
given = reversed("foobar")
other = 6 * tuple(given)
final = "".join(other)
print(final)
Output:
raboofraboofraboofraboofraboofraboof
or
print(6 * "".join(reversed("foobar")))
Output:
raboofraboofraboofraboofraboofraboof
or
print(6 * "foobar"[::-1])
Output:
raboofraboofraboofraboofraboofraboof
but you multiplied a tuple, not an iterator. what i'm suggesting is than if Python had the ability to multiply an iterator, it should make sense for the product to be a new iterator that carries out iterating the multiplicand iterator (maybe a copy of it) that many times. likewise, adding iterators should give a sum iterator that carries out iterating over all the added iterators. subtraction and division would not make sense in most cases. i can imagine comparing iterators and applying len().
itertools.repeat? There are likely other functions in itertools that are useful to you and there are a whole bunch more in the Toolz library.
i'm interested in studying the ways using iterators could be expanded in case some these make good use cases and make sense for how they get used. i think adding any number of iterators might make sense as well as multiplying them by an int. i might try to make a generator that does this.
Maybe I misunderstood what you meant by "multiplying them by an int". In any case, did you look at the libraries I mentioned? There's a lot of useful stuff in both.
i have looked at itertools. i've used a few several times even before starting this thread. anything in particular you think i should look at?
Just knowing that it exists really and checking there first to see if there's something that solves a problem for you, before you reinvent the wheel. The same goes for Toolz.
you are giving me two module names to check. that suggests to me that you don't really know where it is. if you don't that further suggests you don't really know if it does exist.
i cannot find Toolz. itertools.repeat might be the closest in concept but it just gives a repetition of iterators, not one iterator that has all the repetition inside.