[Tutor] How can I replicate a list in a for loop
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 4 13:38:18 CET 2015
On 04/02/15 09:46, Suresh Kumar wrote:
>>>> print var
> ['a', 'b', 'c', 'd', 'e']
> the user gave two so code should be like this
>>>> for i in itertools.product(var,var):
> print i[0]+i[1]
> output of code should be like this
> aa
> ab
...
> ee
> based on the user given input of length i need to add var in for loop
> if 3 given
>>>> for i in itertools.product(var,var,var):
> print i[0]+i[1]+i[2]
OK, So the question is how to pass n copies of var to product()?
You could do it by enclosing var in an outer list or tuple, then
unpacking the result in the call to product():
Untested...
for i in itertools.product(*((var,) * n)):
print ''.join(i)
Does that work?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list